MATLAB Answers

How to find and print elements of a character array?

8 views (last 30 days)
Amith Mallya
Amith Mallya on 22 Apr 2021
Commented: Amith Mallya on 23 Apr 2021
Hello everyone,
This is the first time im dealing with words in matlab
I need help to print a character string
eg
mem=['ISNT-60','ISA55-55-6 b/b','ISMC-100 b/b','ISMC-125 b/b','ISMB-225','ISMC-175 b/b','ISHB-250','ISMB-400'];
d=[1,5,8,5,4,2,4];
I want to matllab to print character strings in char array matrix (mem) based on elemts in matrix d
i.e mem(d(i)) for i=1 to 7
so say mem(d(1))= ISNT-60
function opt=dcde(A1,mem)
c=dec2bin(A1(1),21);
i=1;
count=1;
while count<20
d=c(count:count+2);
d=bin2dec(d)
opt=(mem(d));
fprintf('member id %d, :%f \n',i,opt);
count=count+3;
i=i+1;
end
end
This code takes a number as inputs converts it into 21 igit binary splits it into 3 digit data points (represeted by matrix d)
based on the value of 3 digit code i want to print name of the section given in matrix mem
This code is printing a number rather than a character string and i dont understand why

Accepted Answer

David Hill
David Hill on 22 Apr 2021
Use a cell array instead.
mem={'ISNT-60','ISA55-55-6 b/b','ISMC-100 b/b','ISMC-125 b/b','ISMB-225','ISMC-175 b/b','ISHB-250','ISMB-400'};
mem{3}

More Answers (1)

DGM
DGM on 22 Apr 2021
Edited: DGM on 22 Apr 2021
Is there some reason that you need to keep all the strings concatenated into one long character vector? Why not store them in a cell array? Also, you'll need to handle cases where there are '000' runs in c, otherwise you'll wind up with errors. As to why you were getting numbers out, you're trying to display a character string as a floating point number (%f).
mem={'ISNT-60','ISA55-55-6 b/b','ISMC-100 b/b','ISMC-125 b/b','ISMB-225','ISMC-175 b/b','ISHB-250','ISMB-400'};
A1=299666 % this particular number converts to a binary string without any zero triplets
c=dec2bin(A1(1),21);
i=1;
count=1;
while count<20
d=c(count:count+2);
d=bin2dec(d)
if d==0
% do something different, because zero isn't a valid index
else
opt=(mem{d});
fprintf('member id %d, :%s \n',i,opt);
end
count=count+3;
i=i+1;
end
  1 Comment
Amith Mallya
Amith Mallya on 23 Apr 2021
No reason to take character array, this is the 1st time i am using character strings, so was confused,
Thank you for pointing out the problem with 000 , i deal with it by adding 1 to d (as i have 8 options for mem), i missed it in this code,
Thanks for your quick reply

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by