필터 지우기
필터 지우기

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

채택된 답변

Stephen23
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
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!

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by