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!