Effacer les filtres
Effacer les filtres

decimal increment in a for loop

3 vues (au cours des 30 derniers jours)
www
www le 17 Mar 2016
Commenté : Star Strider le 17 Mar 2016
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.

Réponse acceptée

Star Strider
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
www
www le 17 Mar 2016
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 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

Connectez-vous pour commenter.

Plus de réponses (0)

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!

Translated by