フィルターのクリア

Check class of input variables

5 ビュー (過去 30 日間)
Ledger Yu
Ledger Yu 2018 年 9 月 12 日
編集済み: Stephen23 2018 年 9 月 12 日
I have a function that requires several input variables:
function output = myFun(A,B,C,D,E,...)
% code
end
I need to check the class of those inputs and convert all "cell" to "mat" format. Of course I can do something like this:
if iscell(A)
A = cell2mat(A)
end
if iscell(B)
B = cell2mat(B)
end
if iscell(C)
C = cell2mat(C)
end
...
But how do I do that in a for loop?
  1 件のコメント
Stephen23
Stephen23 2018 年 9 月 12 日
編集済み: Stephen23 2018 年 9 月 12 日
"But how do I do that in a for loop?"
Magically accessing variable names in a loop is one way that beginners force themselves into writing slow, complex, buggy code that is hard to debug. read this to know why:
The situation is easy to avoid with varargin and indexing.

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

回答 (1 件)

Stephen23
Stephen23 2018 年 9 月 12 日
編集済み: Stephen23 2018 年 9 月 12 日
Simply using varargin:
function out = myFun(varargin)
idx = cellfun(@iscell,varargin);
varargin(idx) = cellfun(@cell2mat,varargin(idx),'uni',0);
...
end
You can then access the elements of varargin trivially using indexing.
  2 件のコメント
Ledger Yu
Ledger Yu 2018 年 9 月 12 日
After this, I suppose I should do something like this:
A = varargin{1};
B = varargin{2};
C = varargin{3};
...
or is there an easier way?
Stephen23
Stephen23 2018 年 9 月 12 日
編集済み: Stephen23 2018 年 9 月 12 日
"After this, I suppose I should do something like this:"
A = varargin{1};
B = varargin{2};
C = varargin{3};
I don't suppose that, but you could if you want to. Personally I would not bother, because all of the data is trivially accessibly using indexing already.
"or is there an easier way?"
No. Read my comment to know why:

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

カテゴリ

Help Center および File ExchangeGet Started with MATLAB についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by