How to add columns equally in each page of a multidimensional array within a for loop?
7 次查看(过去 30 天)
显示 更早的评论
I have a problem inside a for loop where I am defining a multidimensional array by adding more columns at every loop. The multidimensional array I have problems with is array R. The starting dimension for k =1 of R is 4425x2x11. At the end of the for loop I should get R of dimension 4425x23x11. Hence, for each k within the loop the array R gets more columns but equally for every page. The for loop for R calculation is following: Omega_rs has size 4425x11.
kmax = 21;
A = 11;
for k = 1:kmax
for i = 1:A
Vkm1 = 2*sum(Omega_rs(:,i).*R(:,k+1,i).*R(:,k,i).*q(:,i));
Sk = Omega_rs(:,i).*R(:,k+1,i)-Vkm1*R(:,k,i);
Dk = sqrt(2*sum((Sk.^2).*q(:,i)));
R(:,:,i) = [R(:,:,i),Sk/Dk,i];
coeff(:,k+2,i) = -Vkm1*coeff(:,k,i);
coeff(2:k+1,k+2,i) = coeff(2:k+1,k+2,i)+coeff(1:k,k+1,i);
coeff(:,k+2,i) = coeff(:,k+2,i)/Dk;
end
end
I have checked the for loop line by line, and it is ok for all variables inside except the R array.. After executing this for loop I get a note Dimensions of matrices being concatenated are not consistent. Any advice how to solve this problem would be greatly appreciated.
Thank you in advance!
2 个评论
Rik
2017-11-23
Sk = Omega_rs(:,i).*R(:,k+1)-Vkm1(:,i)*R(:,k,i); is that correct? Or should it be R(:,k+1 ,i)
Also, pre-allocating your matrices (especially large ones) is generally a good idea.
If that doesn't solve your issue, check all your * and / if they should indeed be non-element-wise operation.
采纳的回答
Rik
2017-11-24
You need to think about what your syntax does.
R(:,:,i) = [R(:,:,i),Sk/Dk,i];
What that line does is evaluating the right hand side and saving to de left hand side. When it evaluates the right hand, this goes wrong. You are trying to concatenate R(:,:,i) (a 2D matrix) with something that is either a matrix or a scalar (you can easily check with the debugging tools) and with a scalar. I don't think there is any implicit expanding for this syntax. What do you want to achieve? Because you can use a syntax like R(:,k,:)=Some_2D_matrix;. You can also look into the permute and cat functions.
Also, I expect you will get an error for i=2, because it looks like Vkm1 is a scalar, so Vkm1(:,i) will result in an error.
3 个评论
Rik
2017-11-24
What you want to do is saving a 4425x1x1 to R. Just do that.
R(:,k+1,i)=Sk/Dk;
%for this syntax it is best to pre-allocate R:
%R=zeros(4425,22,11);
At the end of your loop R will be 4425x22x11
I'm getting the idea you don't understand how concatenation works. The syntax you are using tells Matlab to replace R(:,:,1) with the matrix that is the result of [R(:,:,i),Sk/Dk,i]. That last is the concatenation, but it doesn't affect R, until you save it with the R(:,:,i)=
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!