why are if statements not working?

조회 수: 2 (최근 30일)
Maria Galle
Maria Galle 2020년 12월 9일
댓글: Walter Roberson 2020년 12월 9일
%the if statements are not working when I run the code
Price=[199.54 195.89 195 192 193.29 197.09 197.78 190.34 189.55 193.30...
196 194.60 193.63 193 193.77 195.23 193.97];
Total_Shares=100;
Cash=0;
Fee=10;
Shares=10;
if Price(1:end)>195
a=Total_Shares-Shares
Value=a*Price(1:end)
elseif Price(1:end)<193.50
a=Total_Shares+Shares
Value=a*Price(1:end)
end
if Price(1:end)>195
c=Shares*Price(1:end)
Total_cash=c-Fee
elseif Price(1:end)<193.50
c=Shares*Price(1:end)
Total_cash=c-Fee
end

답변 (2개)

Cris LaPierre
Cris LaPierre 2020년 12월 9일
For an if statement to work as exepcted, the conditional statement must return a single logical result. Yours is returning a result for each value in Price. If you want to perform a computation for each value in Price you should consider placing everything inside a for loop.
You could instead consider removing the if statements and performing the computations using logical indexing.
Consider looking at Chs 12-13 in MATLAB Onramp.
  댓글 수: 5
Stephen23
Stephen23 2020년 12월 9일
It really is about time that this ancient "feature" was retired, it causes far more problems than it has ever solved. Ditto for the "feature" of for-looping over columns.
From my own observation over thousands of lines of code and functions that I have used, tested, and reviewed, I have never seen one single effective use of either of those "features", but I have certainly read on this forum about plenty of bugs caused by them.
Walter Roberson
Walter Roberson 2020년 12월 9일
I have used looping over columns a couple of times. I forget why at the moment, but I do seem to recall that cell arrays were involved.

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


David Hill
David Hill 2020년 12월 9일
Price=[199.54 195.89 195 192 193.29 197.09 197.78 190.34 189.55 193.30...
196 194.60 193.63 193 193.77 195.23 193.97];
Total_Shares=100*ones(size(Price));
Cash=0;
Fee=10;
Shares=10;
Total_cash=0;
Value=100*Price;
Total_Shares(Price>195)=Total_Shares(Price>195)-Shares;
Value(Price>195)=Total_Shares(Price>195).*Price(Price>195);
Total_Shares(Price<193.5)=Total_Shares(Price<193.5)+Shares;
Value(Price<193.5)=Total_Shares(Price<193.5).*Price(Price<193.5);
Total_cash=Total_cash+sum(Shares*Price(Price>195)-Fee)-sum(Shares*Price(Price<193.5)+Fee);

카테고리

Help CenterFile Exchange에서 Financial Toolbox에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by