Is there a way to assign a variable-dimension calculation to an array of generic dimension?
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
dpb
il 30 Giu 2021
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.
Risposta accettata
Matt J
il 30 Giu 2021
Modificato: Matt J
il 30 Giu 2021
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 Commenti
Matt J
il 30 Giu 2021
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
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Resizing and Reshaping Matrices in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!