Matrix Dimension in Subroutine

1 次查看(过去 30 天)
Tom
Tom 2019-8-15
编辑: Tom 2019-8-16
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
  2 个评论
KALYAN ACHARJYA
KALYAN ACHARJYA 2019-8-15
Define/ whos/ any examples??
N,Kn,f??
Tom
Tom 2019-8-16
N and Kn are just scalar values which I pass to the subroutine, and f is a vector which I pass to the subroutine and which is multiplied at the end of the routine with the matrix FF I have created, I am mostly concerned with how to create the matrix FF.

请先登录,再进行评论。

回答(1 个)

Guillaume
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{:}];
  1 个评论
Tom
Tom 2019-8-16
编辑:Tom 2019-8-16
I am trying the following which creates something of the right size
for i=1:100
rij= (p - sing(1:3,i));
FF(1:3, 3*i-2:3*i) =((1/8*pi*Kn)*((eye(3)/norm(rij)) + (rij'*rij)/norm(rij)^3))'; %subroutine to find velocity at the point %
end
although not when I put it in a function to try and get a subroutine for some reason. Also looks like some strange repetitions so not sure if the loop does exactly what I require.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by