Matrix Dimension in Subroutine
1 次查看(过去 30 天)
显示 更早的评论
I am basically trying to write a subroutine where I loop over N vectors called rij and then create a 3*3N array by evaluating each vector with a function which returns a 3*3 matrix, these 3*3 matrices then being putting next to each other in an array until one ends up with a 3*3N array after looping for the N rij vectors. (To clarify, p is a 3x1 column and sing is a 3x100 array which I am viewing as an array of 100 3x1 column vectors.
However, I can't get the matrix dimensions to agree for the matrix FF when I try this, how should I be assigning the indices for the matrix in order to be able to achieve this?
function[v]=StokesletVelocity(N,sing,p,Kn,f)
for i=1:N
rij= (p - sing(1:3,i));
FF(1:3,1:i)=((1/8*pi*Kn)*((eye(3)/norm(rij)) + (rij'*rij)/norm(rij)^3))'; %subroutine to find velocity at the point %
end
v=FF*f;
end
回答(1 个)
Guillaume
2019-8-16
for i=1:N
FF(1:3,1:i) = ...
So, clearly on the first iteration, this means assign something to:
FF(1:3, 1:1) = ... %assign to a 3x1 matrix
on the 2nd iteration:
FF(1:3, 1:2) = ... %assign to a 3x2 matrix. 1 more row than before
etc. Each time you try to assign to something with one more column (also overwriting what was assigned previously).
Of course, if the something is 3x3, assigning it to a 3x1 array is not going to work. Haven't we discussed this with you before?
Now, you could play around with indices, maybe this is what you intended to do:
FF = zeros(3, N*3); %always preallocate your arrays rather than growing in a loop
for i = 1:N
FF(:, (1:3) + 3*(i-1)) = ...
end
But since you seem to be struggling with indexing, it may be simpler to use a cell array as in your previous question, then concatenate everything:
FF = cell(1, N);
for i = 1:N
FF{i} = ...
end
FF = [FF{:}];
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!