How to set an array identifier within code
Show older comments
Hi,
I am trying to write a snippet that takes an input array of any size (I will refer to it as A with N dimensions) and a column or row vector v, that returns an array B having N+1 dimensions, which elements along the (N+1)th dimension are the products A*v(i) (where v(i) are the individual scalar elements in v).
If A is a 2D matrix, it can be done this way:
A=rand(4,5);
v=rand(1,3);
B=zeros([size(A) length(v)]);
for k=1:length(v)
B(:,:,k)=v(k)*A;
end
This works fine but since I need to write as many ' : ' as there are dimensions in A, this is not very versatile.
So I am looking for a way to change this argument as the code executes to adapt to the number of dimensions in A. I have tried the following:
A=rand(4,5);
v=rand(1,3);
bit=sprintf(':,'); %Define the string element to be repeated N times in the argument
arg=bit; %Initiate the argument string
for c=1:(length(size(A))-1)
arg=strcat(arg,bit) %Concatenate as many times as necessary
end
arg=strcat(arg,'k') %Append with the letter k
%In this example, arg is ':,:,k'
B=zeros([size(A) length(v)]);
for k=1:length(v)
B(arg)=v(k)*A;
end
But it doesn't work...
Accepted Answer
More Answers (0)
Categories
Find more on Operators and Elementary Operations 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!