decimal increment in a for loop

5 次查看(过去 30 天)
Hi all, I have this equation inv(A-z.^2*B)*C where A, B are two by two matrix and C is 2 by 1 matrix. The problem is that I want to run the equation for a range of z variables at an increment of 0.1 or 0.001. So I thought, maybe it would be good to use a for loop.
savedata =[];
for i=1:0.1:500
z(i)=i
EQN = inv(A-z(i).^2*B)*C
datasave = [savedata;EQN(1)]
end
This code however, produce an error 'Subscript indices must either be real positive integers or logicals'. Looking forward for some help!
Thank you in advance.

采纳的回答

Star Strider
Star Strider 2016-3-17
I am not certain what you are doing.
This will run your loop:
A = randi(9, 2); % Create Matrix
B = randi(9, 2); % Create Matrix
C = randi(9, 2, 1); % Create Vector
z = 1:0.1:500;
for i=1:length(z)
EQN(:,i) = (A-z(i).^2*B)\C;
end
  2 个评论
www
www 2016-3-17
Hi Polar bear coder! Thank you again for the help T.T . Because I have a range of z = 1:0.0001:100; ,is there a way to make it run faster and then extract only the data from row 1 and plot it against z?
Star Strider
Star Strider 2016-3-17
My pleasure!
I experimented using bsxfun but because ‘z’ is a vector and ‘B’ is (2x2), it is not possible to multiply them except using the loop with element-by-element scalar multiplication in your loop. Replacing your inv call with the mldivide,\ call is the only optimisation I can provide.
Plotting them as you want is straightforward:
A = randi(9, 2); % Create Matrix
B = randi(9, 2); % Create Matrix
C = randi(9, 2, 1); % Create Vector
z = 1:0.1:500;
for i=1:length(z)
EQN(:,i) = (A-z(i).^2*B)\C;
end
figure(1)
plot(z, EQN(1,:)) % Plot First Row
grid

请先登录,再进行评论。

更多回答(0 个)

类别

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