How to set an array identifier within code
显示 更早的评论
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...
采纳的回答
更多回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Operators and Elementary Operations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!