- Your error message can't be reached, because that if is only evaluated if the sizes match. Use else instead.
- The error message is missing a newline at the end.
- You're using clear all.
- You're using i and j as variables. This is not a major issue, but it is better to avoid the habit.
- Your loops don't run for a range of values. Look at how you define them.
- You're using length. You should use size(_,dim) or numel instead.
- You posted your code as an image, so now nobody can edit it for you.
- You store the row and col size of A, but don't do anything with those values. That line also assumes the arrays are 2D or a vector, so it will not work as expected for 3D and higher.
- You're using a nested loop instead of simply using + to do an addition.
- Your error doesn't prevent the addition from running, so another error will be triggered there once you fix your code.
- You aren't initializing C anywhere, so if you remove clear all and not put in something like clear or clearvars there will be values left over in C. Currently this code is unnecessarily slow, as it will have to expand the array dynamically. Read about ones() and zeros().
- You omitted the semicolon inside your loop, so C will be printed after each addition, creating clutter in your command window and slowing down your code.
help with matrix addition and for loops
8 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/352766/image.jpeg)
I need the code to both tell me if the vectors match and if not it needs to display a error message, also when I run this code either it wont work and only give me the first variable in the C vector or it will give me the right vector but give me two more rows of numbers that I can not figure out where they are coming from.
0 commentaires
Réponses (1)
Rik
le 28 Août 2020
Modifié(e) : Rik
le 28 Août 2020
There are several issues with your code (not in any particular order):
General advice: make sure there are no orange lines left. Either solve the issue, or (only if you're completely sure there isn't an actual problem) use the %#ok pragma: rightclick on the orange line and select suppress warning. Only the last line where you display C is a candidate for this. All other issue the linter is pointing out should be solved.
0 commentaires
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!