How to present elements of a cell array?
2 ビュー (過去 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!