adding answers into cell array
조회 수: 2 (최근 30일)
이전 댓글 표시
so i have a loop function that everytime it runs generates an output. example:
res = 'random words'
next time it runs...
res = 'another answer'
again...
res = 'another answer'
etc...so everytime it runs and generates an answer (some may be the same), I would like to record it. The end goal being that it lists all the outputs (without repeating any!) in a cell array format.
like so:
{'random words'} {'another answer'}
any sugguestions for how to go about getting these results all into an cell array? currently it just gives me an output of whatever the last result was and i want to have all the results.
댓글 수: 0
채택된 답변
Voss
2022년 4월 1일
One way:
answers = {};
for n = 1 : 10
% My very complex computation
res = sprintf('The answer is %i', randi(5));
answers{end+1} = res;
end
answers % showing answers with duplicates for reference
answers = unique(answers,'stable') % final result
Another way:
answers = {};
for n = 1 : 10
% My very complex computation
res = sprintf('The answer is %i', randi(5));
if ~ismember(res,answers)
answers{end+1} = res;
end
end
answers
댓글 수: 0
추가 답변 (1개)
Riccardo Scorretti
2022년 4월 1일
Hi. You could do like this:
answers = {};
for n = 1 : 10
% My very complex computation
res = sprintf('The answer is %i', n);
answers{end+1} = res;
end
answers
참고 항목
카테고리
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!