decimal increment in a for loop
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
Star Strider
le 17 Mar 2016
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 commentaires
Star Strider
le 17 Mar 2016
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
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!