decimal increment in a for loop

조회 수: 4 (최근 30일)
www
www 2016년 3월 17일
댓글: Star Strider 2016년 3월 17일
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