Calling matrix values to strings
1 view (last 30 days)
Show older comments
Hi, I want to write a string of letters and then define a vector that will assign numerical values to each of the letters: e.g.
>> string='zxcv'
string =
zxcv
then define a vector which allows me to assign number to the string elements and add them:
vector=[1 4 6 -9 2 7 23 -6 -8 9 10 13 4 5 -8 -12 -2 1 0 11 -8 -9 3 8 9 2];
if string(1)=z
output=vector(2)+vector(4)
disp(output)
Matlab has a problem mainly with this line - if string(1)=1
Any clues?
0 Comments
Accepted Answer
Stephen23
on 15 Nov 2015
Edited: Stephen23
on 15 Nov 2015
In MATLAB the equality operator is ==, not =. This is clearly shown in the documentation (see link I gave). The single equals sign is only used to assign a value to a variable.
vector = [1,4,6,-9,2,7,23,-6,-8,9,10,13,4,5,-8,-12,-2,1,0,11,-8,-9,3,8,9,2];
string = 'zxcv';
if string(1)=='z' % note == not =
output = vector(2)+vector(4);
disp(output)
end
displays this:
-5
Note that for testing strings it is recommended to use strcmp or strncmp instead of array equals:
>> strncmp(string,'z',1)
rather than this:
>> string(1)=='z'
More Answers (0)
See Also
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!