Suitable input for a function handle

1 回表示 (過去 30 日間)
Mohammad Shojaei Arani
Mohammad Shojaei Arani 2022 年 2 月 4 日
コメント済み: Walter Roberson 2022 年 2 月 4 日
Hellow friends,
I need to do something which I explain through a simple example. Consider the following
F=@(x,y,z)[x.*z.^2.*y;3.*x-y-2.*z;x.^2+y.^2+z.^2];
A1=[1 2 3];B1=num2cell(A1);
A2=[4 5 6];B2=num2cell(A2);
F(B1{:})
F(B2{:})
ans =
18
-5
14
ans =
720
-5
77
Now, I desire to do all the above calculations at once. I mean, I wish to do something as bellow (which throughs error)
>> A=[1 2 3;4 5 6];
B=num2cell(A);
F(B)
Not enough input arguments.
Error in @(x,y,z)[x.*z.^2.*y;3.*x-y-2.*z;x.^2+y.^2+z.^2]
I wish to get the following answer:
18 720
-5 -5
14 77
Any idea?
Thanks in advance,
Babak

採用された回答

Walter Roberson
Walter Roberson 2022 年 2 月 4 日
F = @(x,y,z)[x.*z.^2.*y;3.*x-y-2.*z;x.^2+y.^2+z.^2];
A = [1 2 3;4 5 6];
B = cellfun(@transpose, num2cell(A, 1), 'uniform', 0)
B = 1×3 cell array
{[1 4]} {[2 5]} {[3 6]}
F(B{:})
ans = 3×2
18 720 -5 -5 14 77
  3 件のコメント
Steven Lord
Steven Lord 2022 年 2 月 4 日
Another approach would involve breaking A up into appropriately sized pieces using mat2cell.
Walter Roberson
Walter Roberson 2022 年 2 月 4 日
num2cell() is basically an easier interface around mat2cell.
output = num2cell(A, 1)
is
tsize = size(A);
nd = length(tsize);
temp = cell(1,nd);
temp{1} = ones(1,tsize(1));
for K = 2 : nd; temp{K} = tsize(K); end
output = mat2cell(A, temp{:})
(The code can be made shorter under the assumption that A has exactly 2 dimensions.)

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeAxis Labels についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by