How to present elements of a cell array?
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
dpb
il 25 Mag 2014
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
il 28 Set 2017
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"?
Risposta accettata
the cyclist
il 25 Mag 2014
Modificato: the cyclist
il 25 Mag 2014
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))
2 Commenti
Più risposte (1)
Cedric
il 25 Mag 2014
Modificato: Cedric
il 25 Mag 2014
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 Commento
the cyclist
il 25 Mag 2014
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.
Vedere anche
Categorie
Scopri di più su Data Import and Analysis in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!