Code will not display getting error

2 vues (au cours des 30 derniers jours)
David Hughes
David Hughes le 16 Juil 2015
Commenté : David Hughes le 16 Juil 2015
I am getting an error on line 14 it will not display B. Any suggestions? This is the code:
A=[1 2 3;4 5 6;7 8 9]
[m,n]=size(A);
while j<=n
i=1;
sum1=0;
while i<=m
sum1=sum1+A(i,j);
B(i,j)=sum1;
i=i+1;
end
j=j+1;
end
disp(B)

Réponse acceptée

the cyclist
the cyclist le 16 Juil 2015
I could not run your code, because j is not yet defined before you enter the loop. I initialized j to 1, and then it worked (and displayed B):
A=[1 2 3;4 5 6;7 8 9]
[m,n]=size(A);
j=1;
while j<=n
i=1;
sum1=0;
while i<=m
sum1=sum1+A(i,j);
B(i,j)=sum1;
i=i+1;
end
j=j+1;
end
disp(B)
But I don't know if that's exactly what you need.
  1 commentaire
David Hughes
David Hughes le 16 Juil 2015
Yes, that is what I needed. I didn't see j wasn't initialized. Thanks

Connectez-vous pour commenter.

Plus de réponses (1)

Steven Lord
Steven Lord le 16 Juil 2015
When you ask about an error, you should include the full, exact text of the error message rather than paraphrasing it.
But in this case, I suspect I know what's going on. What if j <= n is false when you reach your WHILE loop? The body of the WHILE loop will never execute. If B did not exist when you reach your WHILE loop, that will mean it won't exist when you try to display it. [That would mean that if j <= n was true that it was created inside the loop the first time you tried to assign into it. You should avoid doing that; search the documentation for the term "preallocation" for more information.]

Catégories

En savoir plus sur Performance and Memory dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by