How do I get the output to only show once, if there is only one output to be shown?
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Stephen23
2015-5-23
编辑:Stephen23
2015-5-25
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!