Suitable input for a function handle
1 view (last 30 days)
Show older comments
Mohammad Shojaei Arani
on 4 Feb 2022
Commented: Walter Roberson
on 4 Feb 2022
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 Comments
Accepted Answer
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)
F(B{:})
3 Comments
Steven Lord
on 4 Feb 2022
Another approach would involve breaking A up into appropriately sized pieces using mat2cell.
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.)
More Answers (0)
See Also
Categories
Find more on Axis Labels 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!