How to present elements of a cell array?
조회 수: 1 (최근 30일)
이전 댓글 표시
If in any two elements of both cells, the numbers are the same, then how to display the letters that correspond to these numbers? For example:
s1 = {‘EC 101’, ‘CH 100’, ‘MA 115’};
s2 = {‘CH 100’, ‘MA 112’, ‘BI 101’};
Print to the screen:
EC and BI.
CH and CH
댓글 수: 2
dpb
2014년 5월 25일
Are the formats of the cells always as shown?
Simpler would be if you could create the cell arrays as character, number instead of as mixed when generating them.
Well wait for answers to above before actually spending time...
Jim Bosley
2017년 9월 28일
For the love of Mike, I can't be the only person that this affects: Why in the world do your code examples include left and right apostrophes? This precludes being able to copy and paste from MATLAB help to MATLAB, and is a needless barrier to help being useful. Perhaps I'm missing something? IS there a way to tell MATLAB "treat all apostrophes as straight apostrophes"?
채택된 답변
the cyclist
2014년 5월 25일
편집: the cyclist
2014년 5월 25일
As alluded to by dpb, I made some assumptions about your format.
s1 = {'EC 101', 'CH 100', 'MA 115'};
s2 = {'CH 100', 'MA 112', 'BI 101'};
% Extract the last three characters of each cell, and store as a numeric array.
n1 = cellfun(@(x)str2num(x(end-2:end)),s1);
n2 = cellfun(@(x)str2num(x(end-2:end)),s2);
% Identify which numbers from n1 are also in n2, and get the indices
[tf,idx] = ismember(n1,n2);
% Keep only the indices of s1 that have elements in s2.
s1 = s1(tf);
% Keep only the corresponding element of s2, in proper order.
s2 = s2(idx(tf));
% Extract the first two characters of the sorted cells
first = cellfun(@(x)x([1 2]),s1,'UniformOutput',false)';
second = cellfun(@(x)x([1 2]),s2,'UniformOutput',false)';
% Munge them together with the word "and", and display
output = char(arrayfun(@(x,y)[x{:},' and ',y{:}],first,second,'UniformOutput',false))
추가 답변 (1개)
Cedric
2014년 5월 25일
편집: Cedric
2014년 5월 25일
s1n = reshape(sscanf([s1{:}],'%s%d'),3,[]) ;
s2n = reshape(sscanf([s2{:}],'%s%d'),3,[]) ;
[id2,id1] = find(bsxfun(@eq,s1n(3,:),s2n(3,:).') ;
output = arrayfun(@(i1,i2)sprintf('%s and %s',s1n(1:end-1,i1),...
s2n(1:end-1,i2)),id1,id2,'UniformOutput',false)
Your move, The Cyclist ;-)
Painfully Created with MATLAB® Mobile™
댓글 수: 1
the cyclist
2014년 5월 25일
Yours crushes mine on timing (factor of 5 on my machine), so I'll bow to this. Any "improvements" would carry with them some serious obfuscations, like dispensing with the reshape commands in favor of more clever indexing, etc.
참고 항목
카테고리
Help Center 및 File Exchange에서 Data Import and Analysis에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!