How do I get the output to only show once, if there is only one output to be shown?
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Cyrus Ahmadi
am 23 Mai 2015
Bearbeitet: Stephen23
am 25 Mai 2015
The problem given was "Write a function speciescounts that takes a cell array of species names as input and returns a 2-column cell array with names and frequencies of the species contained in the input. The first column of the output will contain the unique set of species names, in the same order as they appear in the input. The second column of the output will contain the frequency of each species."
My code successfully analyzes the input cell array; however, lets say the input cell array is {'hello' 'hello' 'hello' 'hello'}
it outputs:
'hello' [4] 'hello' [4] 'hello' [4] 'hello' [4]
I would like it to output just:
'hello' [4]
here is what I have so far:
function out = speciescounts(in)
out = cell(numel(in),2);
for i = 1:numel(in)
out{i,1} = in{i};
out{i,2} = numel(find(strcmp(in,in{i})));
end
0 Kommentare
Akzeptierte Antwort
Stephen23
am 23 Mai 2015
Bearbeitet: Stephen23
am 25 Mai 2015
The concept has a major flaw: the loop iterates over each element in the input arrays and creates one pair of output values on each iteration. This means, as you have found out, even if the input consists of the only one string repeated it does not adjust the output to the number of unique strings.
Doing things in loops is useful on low-level languages, but often in MATLAB there is a neater and faster method using vectorized code. Consider the fucntion unique, especially its indices outputs:
>> A = {'hello','world','hello','hello','world'};
>> [B,C,D] = unique(A,'stable')
B =
'hello' 'world'
C =
4 5
D =
1 2 1 1 2
>> E = hist(D,numel(C))
E =
3 2
And there is most of a solution, in just two lines!
0 Kommentare
Weitere Antworten (0)
Siehe auch
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!