adding answers into cell array

2 ビュー (過去 30 日間)
Elena
Elena 2022 年 4 月 1 日
回答済み: Voss 2022 年 4 月 1 日
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.

採用された回答

Voss
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 = 1×10 cell array
{'The answer is 2'} {'The answer is 1'} {'The answer is 3'} {'The answer is 2'} {'The answer is 5'} {'The answer is 5'} {'The answer is 5'} {'The answer is 3'} {'The answer is 3'} {'The answer is 5'}
answers = unique(answers,'stable') % final result
answers = 1×4 cell array
{'The answer is 2'} {'The answer is 1'} {'The answer is 3'} {'The answer is 5'}
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
answers = 1×5 cell array
{'The answer is 4'} {'The answer is 1'} {'The answer is 5'} {'The answer is 3'} {'The answer is 2'}

その他の回答 (1 件)

Riccardo Scorretti
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
answers = 1×10 cell array
{'The answer is 1'} {'The answer is 2'} {'The answer is 3'} {'The answer is 4'} {'The answer is 5'} {'The answer is 6'} {'The answer is 7'} {'The answer is 8'} {'The answer is 9'} {'The answer is 10'}
  1 件のコメント
Elena
Elena 2022 年 4 月 1 日
how can i get unique answers? so none are respeated but still keeps it in the same order?

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by