decimal increment in a for loop
조회 수: 4 (최근 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.
댓글 수: 0
채택된 답변
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
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 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!