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 CenterFile Exchange에서 Axis Labels에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by