Divide elements of matrix by scalar

조회 수: 22 (최근 30일)
Sarah Gomez
Sarah Gomez 2022년 3월 3일
댓글: Sarah Gomez 2022년 3월 3일
for i = 1:N
P(i) = P(i)/2;
end
I have this for loop that's supposed to divide each element of P by two, then I graph P but it's always double what it needs to be. N is 120 and P is a 1x120 array so it's not an indexing problem.
When I isolate my P array in another script and divide each element by 2 my graph looks how I want it to
Why won't my intial code divide by 2? Any help is greatly appreciated.

답변 (1개)

the cyclist
the cyclist 2022년 3월 3일
Are you doing this for loop inside a function? If so, the operation you are doing is only on the local copy of P. You need to output that new value of P from the function. Something like
function P = divideByTwo(P)
for i = 1:N
P(i) = P(i)/2;
end
end
  댓글 수: 1
Sarah Gomez
Sarah Gomez 2022년 3월 3일
Yea, I fixed my problem everything was inside a loop. Took my loop out and eveyrthing worked. Thank you though!

댓글을 달려면 로그인하십시오.

카테고리

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