Effacer les filtres
Effacer les filtres

How do I get the output to only show once, if there is only one output to be shown?

2 vues (au cours des 30 derniers jours)
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

Réponse acceptée

Stephen23
Stephen23 le 23 Mai 2015
Modifié(e) : Stephen23 le 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
And have a look at the function hist (or its newer alternatives):
>> E = hist(D,numel(C))
E =
3 2
And there is most of a solution, in just two lines!

Plus de réponses (0)

Catégories

En savoir plus sur Programming dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by