Is there a way to assign a variable-dimension calculation to an array of generic dimension?
조회 수: 1 (최근 30일)
이전 댓글 표시
I am creating two functions, I'll refer to them as "A" and "B", that each call a third function I'll refer to as "C".
Function C performs an array calculation on an inputted array of any dimension. The output dimension needs to depend on the input dimension. (See MWE below).
Function A inputs a vector into C, Function B inputs a matrix into C. Because these are used in simulation of a system (i.e. called many times), I would like to avoid an "if-statement" in "Cfunction". Is there a way to generically assign the calcuations to Output so that its dimension is determined by the dimension of the RHS of the equation?
Something like:
Output(1,~)= 2*Xinput;
Output(2,~)=5*Xinput;
Or if this is not possible, any tips for accomplishing my goal efficiently. Needless to say my real "Cfunction" is far more complex than my example below - hence the desire to avoid errors by calling the same function in A and B.
Thanks!
function Afunction
X=[1 2 3];
D=Cfunction(X)
end
function Bfunction
X = [1 2 3; 4 5 6]
D=Cfunction(X)
end
function Output=Cfunction(Xinput)
if ndims(Xinput)==2
Output(1,:,:)=2*Xinput;
Output(2,:,:)=5*Xinput;
elseif ndims(Xinput)==1
Output(1,:)=2*Xinput;
Output(2,:)=5*Xinput;
end
end
댓글 수: 2
dpb
2021년 6월 30일
As written, D will be reallocated to whatever the size() of the array Cfunction returns because there are no subscripting expressions so the whole array is reallocated on assignment.
As far as the sample Cfuncton, ndims() can NEVER return <2 so the elseif clause is never going to be invoked--if the idea is whether the input is a vector or an array, then use isvector(Xinput)
The example is probably too simplified to get at the real use I'm guessing, but if the calling sequence in the consumer of the subject function is actually as written above, then it makes no difference at all because the whole LHS variable is written.
채택된 답변
Matt J
2021년 6월 30일
편집: Matt J
2021년 6월 30일
This will work independently of the dimension of Xinput:
function Output=Cfunction(Xinput)
Output(2,:)=5*Xinput(:);
Output(1,:)=2*Xinput(:);
Output=reshape(Output, [size(Output,1) , size(Xinput)] );
end
댓글 수: 3
Matt J
2021년 6월 30일
Yes. Actually, though, if you have pre-allocated Output (which you probably should do), then the call to reshape() becomes unnecessary.
function Output=Cfunction(Xinput)
Output=nan([2,size(Xinput)]); %pre-allocate
Output(1,:)=2*Xinput(1,:);
Output(2,:)=3*Xinput(2,:);
end
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!