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!