Suitable input for a function handle
1 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
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)
F(B{:})
3 个评论
Steven Lord
2022-2-4
Another approach would involve breaking A up into appropriately sized pieces using mat2cell.
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 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!