필터 지우기
필터 지우기

help with matrix addition and for loops

조회 수: 11 (최근 30일)
Steve Avilesmejia
Steve Avilesmejia 2020년 8월 28일
편집: Rik 2020년 8월 28일
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.

답변 (1개)

Rik
Rik 2020년 8월 28일
편집: Rik 2020년 8월 28일
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.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by