フィルターのクリア

Creating a piecewise function

1 回表示 (過去 30 日間)
Ali Kiral
Ali Kiral 2021 年 6 月 14 日
コメント済み: Ali Kiral 2021 年 6 月 14 日
I am trying to make that triangular wave for one period with the code (I don't want to plot it, just to generate x and y values in the interval)
x = 0 : 0.5 : 4;
for k = 1 : length(x)
if x(k) < 1
y(k) = 0;
elseif x(k) >= 1 & x(k) < 2
y(k) = x-1;
elseif x(k) >=2 & x(k) < 3
y(k) = 3-x;
elseif x(k)>=3
y(k) = 0;
end
end
Then Matlab returns 'In an assignment A(I) = B,...' I think I am not trying to assign a scalar to a vector or vice versa, what is the problem here?

採用された回答

Voss
Voss 2021 年 6 月 14 日
The line:
y(k) = x-1;
tries to assign the entire vector x-1 to a single element (the kth element) of y. Instead it should be:
y(k) = x(k)-1;
Similarly the line:
y(k) = 3-x;
should be:
y(k) = 3-x(k);
  1 件のコメント
Ali Kiral
Ali Kiral 2021 年 6 月 14 日
Got it, thanks

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

その他の回答 (1 件)

Scott MacKenzie
Scott MacKenzie 2021 年 6 月 14 日
A few bugs in your code. Here's the fix (although there are easier ways to do this):
x = 0 : 0.5 : 4;
for k = 1 : length(x)
if x(k) < 1
y(k) = 0;
elseif x(k) < 2
y(k) = x(k)-1;
elseif x(k) < 3
y(k) = 3-x(k);
else
y(k) = 0;
end
end
plot(y);
  1 件のコメント
Ali Kiral
Ali Kiral 2021 年 6 月 14 日
Thank you

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

カテゴリ

Help Center および File ExchangeGet Started with MATLAB についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by