Hey all newbie to matlab, was wondering what I can do to fix the "for loop" code I have below, I am getting the "array indices must be positive integers." Thanks in advance!

1 回表示 (過去 30 日間)
clear;
counter = 0;
for t = -15:0.2:15;
y(t) = counter;
counter = ((t^4)-(3*t^2)+(2*t)-1)
end;

採用された回答

DGM
DGM 2021 年 9 月 29 日
Try this:
counter = 0;
t = -15:0.2:15;
y = zeros(size(t));
for k = 1:numel(t)
y(k) = counter;
counter = ((t(k)^4)-(3*t(k)^2)+(2*t(k))-1);
end
That said, you don't really need a loop to do this:
y2 = (t.^4 - 3*t.^2 + 2*t - 1);
y2 = [0 y2(1:end-1)];
immse(y,y2) % show that the two results are identical

その他の回答 (1 件)

Kevin Holly
Kevin Holly 2021 年 9 月 29 日
clear;
counter = 0;
y=[];
for t = -15:0.2:15;
y = [y; counter];
counter = ((t^4)-(3*t^2)+(2*t)-1);
end
The indices for the array cannot be a negative number and has to be an integer. You cannot have an array with a value indexed at let's say 1.5.
Let's look at the first 3 values in the array
y(1:3)
ans = 3×1
1.0e+04 * 0 4.9919 4.7291
I can view the first value as such:
y(1)
ans = 0
Let's look at the third
y(3)
ans = 4.7291e+04
I cannot view a negative nor integer

カテゴリ

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