why are if statements not working?

5 次查看(过去 30 天)
%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