How to obtain output from function always as cell array even though it would be of size 1

1 回表示 (過去 30 日間)
Jan Chvojka
Jan Chvojka 2022 年 12 月 5 日
コメント済み: Jiri Hajek 2022 年 12 月 6 日
Let's say a function returns a single object or string if there is a single output and a cellarray of them if there are multiple ones e.g. findall() or fullfile(). But this pose a problem if I want to process each output in a for loop because first I need to determine if the output is cellarray or not. Is there a method how to be able to use the following code in all cases, even if N =1 and output be always cell array?
output = findall(...)
for i = 1:N
y = [ output{i} + ...];
end
( a cell array and we dont know in advance what the size will be. In many cases, I dont know in advance how many output parameters a function returns

回答 (1 件)

Jiri Hajek
Jiri Hajek 2022 年 12 月 5 日
Hi,
since you are unsure about the type of a variable, you can solve this by adding a condition:
for i = 1:N
if iscell(output)
y = [ output{i} + ...];
else
y = {output}
end
end
  2 件のコメント
Jan Chvojka
Jan Chvojka 2022 年 12 月 5 日
Well, I usually proceed as you suggested (testing if its cell array). My question was rather - is it possible to solve it more elegant way without another condition? It doesn't seem like a complex problem so I find tedious and unnecessary to further complicate the code by adding if else statemts. I endedup writing a simple function tocell() that wraps the if else statements and produce the "prefered" cellarray format of the output variable everytime based on what does it contain...
Jiri Hajek
Jiri Hajek 2022 年 12 月 6 日
Well, it was not entirely clear that this is not a beginners question, so sorry for providing just the first available option. Fact is, I've struggled in the past with a similar problem myself and found several implicit types of behaviour that can disturb the expected outcome, exactly as you suggested. In some cases even variable viewer can be misleading, so after some trials Ive concluded that for this problem, the simplest foolproof option is also the best.

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

カテゴリ

Help Center および File ExchangeData Type Identification についてさらに検索

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by