Array indices must be positive integers or logical values.

1 回表示 (過去 30 日間)
Michael Ryan
Michael Ryan 2021 年 10 月 25 日
コメント済み: Michael Ryan 2021 年 10 月 25 日
Can't seem to figure out the reason for the error. The array indices, i, as far as I can tell are intergers between 1 and 1000.
Attached is the code:
clear
clc
close all
t = linspace(0,2,1000);
f = zeros(1,length(t));
for i = 1:length(t)
if t(1i) <= 1
f(1i) = 2-(2.*((t(1i)-1).^2));
elseif t(1i) > 1
f(1i) = 0;
end
end
plot(t,f)
Returns the error:
Array indices must be positive integers or logical values.
Error in aufgabe1 (line 10)
f(1i) = 2-(2.*((t(1i)-1).^2));

採用された回答

Scott MacKenzie
Scott MacKenzie 2021 年 10 月 25 日
編集済み: Scott MacKenzie 2021 年 10 月 25 日
You've got a typo in your code. Change the indices
1i
to
i
  1 件のコメント
Michael Ryan
Michael Ryan 2021 年 10 月 25 日
Thanks. This worked. For some reason previously MATLAB was telling me to replace i or j with 1i or 1j.

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

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2021 年 10 月 25 日
t = linspace(0,2,1000);
t is a (real) vector of length 1000
if t(1i) <= 1
That asks to index the vector t at location 1i . However, 1i means sqrt(-1) which is not real-valued and is not a positive integer.
  1 件のコメント
Walter Roberson
Walter Roberson 2021 年 10 月 25 日
t = linspace(0,2,1000);
nt = length(t);
f = zeros(1,nt);
for K = 1:nt
if t(K) <= 1
f(K) = 2-(2.*((t(K)-1).^2));
elseif t(K) > 1
f(K) = 0;
end
end
plot(t,f)
ylim([-1 3])

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

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by