Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a translator in MatLab

Tags:

matlab

I am trying to create a simple program in Matlab where the user can input a string (such as "A", "B", "AB" or "A B") and the program will output a word corresponding to my letter.

Input | Output
A        Hello
B        Hola
AB       HelloHola
A B      Hello Hola

This is my code:

A='Hello'; B='Hola';
userText = input('What is your message: ', 's');
userText = upper(userText);

    for ind = 1:length(userText)
        current = userText(ind);
        X = ['The output is ', current];
        disp(X);

    end

Currently I don't get my desired results. I instead get this:

Input | Output
A       The output is A
B       The output is B

I'm not totally sure why X = ['The output is ', current]; evaluates to The output is A instead of The output is Hello.


Edit:

How would this program be able to handle numbers... such as 1 = "Goodbye"

like image 676
user3089676 Avatar asked Dec 12 '13 13:12

user3089676


2 Answers

What's going on:

%// intput text
userText = input('What is your message: ', 's');

%// ...and some lines later
X = ['The output is ',  userText];

You never map what you type to what is contained by the variables A and B.

The fact that they are called A and B has nothing to do with what you type. You could call them C and blargh and still get the same result.

Now, you could use eval, but that's really not advisable here. In this case, using eval would force the one typing in the strings to know the exact names of your variables...that's a portability, maintainability, security, etc. disaster waiting to happen.

There are better solutions possible, for instance, create a simple map:

map = {
    'A'   'Hello'
    'B'   'Hola'
    '1'   'Goodbye'
};

userText = input('What is your message: ', 's');
str = map{strcmpi(map(:,1), userText), 2};

disp(['The output is ', str]);
like image 77
Rody Oldenhuis Avatar answered Oct 21 '22 02:10

Rody Oldenhuis


I would recommend using a map object to contain what you want. This will circumvent the eval function (which I suggest avoiding like the plague). This is pretty simple to read and understand, and is pretty efficient especially in the case of a long input string.

translation = containers.Map()
translation('A') = 'Hola';
translation('B') = 'Hello';
translation('1') = 'Goodbye';

inputString = 'ABA1BA1B11ABBA';

resultString = '';
for i = 1:length(inputString)
    if translation.isKey(inputString(i))
        % get mapped string if it exists
        resultString = [resultString,translation(inputString(i))];
    else
        % if mapping does not exist, simply put the input string in (covers space case)
        resultString = [resultString,inputString(i)];
    end
end 
like image 2
MZimmerman6 Avatar answered Oct 21 '22 02:10

MZimmerman6