How to find and print elements of a character array?

7 次查看(过去 30 天)
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

采纳的回答

David Hill
David Hill 2021-4-22
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}

更多回答(1 个)

DGM
DGM 2021-4-22
编辑:DGM 2021-4-22
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 个评论
Amith Mallya
Amith Mallya 2021-4-23
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

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by