Divide elements of matrix by scalar
11 次查看(过去 30 天)
显示 更早的评论
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.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/912545/image.jpeg)
When I isolate my P array in another script and divide each element by 2 my graph looks how I want it to
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/912550/image.jpeg)
Why won't my intial code divide by 2? Any help is greatly appreciated.
0 个评论
回答(1 个)
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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!