Suitable input for a function handle

2 views (last 30 days)
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

Accepted Answer

Walter Roberson
Walter Roberson on 4 Feb 2022
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 Comments
Steven Lord
Steven Lord on 4 Feb 2022
Another approach would involve breaking A up into appropriately sized pieces using mat2cell.
Walter Roberson
Walter Roberson on 4 Feb 2022
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.)

Sign in to comment.

More Answers (0)

Categories

Find more on App Building in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!