why are if statements not working?

5 visualizaciones (últimos 30 días)
Maria Galle
Maria Galle el 9 de Dic. de 2020
Comentada: Walter Roberson el 9 de Dic. de 2020
%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

Respuestas (2)

Cris LaPierre
Cris LaPierre el 9 de Dic. de 2020
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 comentarios
Stephen23
Stephen23 el 9 de Dic. de 2020
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 el 9 de Dic. de 2020
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.

Iniciar sesión para comentar.


David Hill
David Hill el 9 de Dic. de 2020
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);

Categorías

Más información sobre Financial Toolbox en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by