help with matrix addition and for loops

5 views (last 30 days)
Steve Avilesmejia
Steve Avilesmejia on 28 Aug 2020
Edited: Rik on 28 Aug 2020
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.

Answers (1)

Rik
Rik on 28 Aug 2020
Edited: Rik on 28 Aug 2020
There are several issues with your code (not in any particular order):
  1. Your error message can't be reached, because that if is only evaluated if the sizes match. Use else instead.
  2. The error message is missing a newline at the end.
  3. You're using clear all.
  4. You're using i and j as variables. This is not a major issue, but it is better to avoid the habit.
  5. Your loops don't run for a range of values. Look at how you define them.
  6. You're using length. You should use size(_,dim) or numel instead.
  7. You posted your code as an image, so now nobody can edit it for you.
  8. 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.
  9. You're using a nested loop instead of simply using + to do an addition.
  10. Your error doesn't prevent the addition from running, so another error will be triggered there once you fix your code.
  11. 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().
  12. 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.
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.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!