How do I create a loop for an equation using if statements?

1 回表示 (過去 30 日間)
Goncalo Costa
Goncalo Costa 2021 年 11 月 9 日
編集済み: Jan 2021 年 11 月 9 日
I want to define an equation/function, to later plot, that changes every cycle. If we consider each cycle to last for example 2 seconds, I want the equation to be defined as:
  • x = y for the first cycle (from t=0s to t=2s);
  • x = -y for every even number cycle (from t=2s to t=4s, from t=6s to t=8s, etc)
  • x= c, where c is a constant for every odd number cycle (from t=4s to t=6s, from t=8s to t=10s, etc)
Initially, I thought of using if statements like here, but this would require making an if statement for each cycle, and therefore if I required a large number of cycles to be plotted the if statement would be very long.
How can I write this down in a way that I don't require a statement for each cycle to be plotted/equated?
  1 件のコメント
Cris LaPierre
Cris LaPierre 2021 年 11 月 9 日
Take a look at Ch 13 of MATLAB Onramp. It introduces both if statements and for loops.

サインインしてコメントする。

回答 (1 件)

Jan
Jan 2021 年 11 月 9 日
編集済み: Jan 2021 年 11 月 9 日
Use "logical indexing":
y = rand(1, 100);
t = 0:99; % Prefer the cyclenumber, not the seconds
c = 17;
index = (t == 0);
x(index) = y(index);
index = (t > 0) & (rem(t, 2) == 0);
x(index) = -y(index);
index = (t > 0) & (rem(t, 2) == 1);
x(index) = c;

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by