How to find and print elements of a character array?

조회 수: 7 (최근 30일)
Amith Mallya
Amith Mallya 2021년 4월 22일
댓글: Amith Mallya 2021년 4월 23일
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