Array indices must be positive integers or logical values.

2 次查看(过去 30 天)
I am trying to plot a v-t graph which pwm(t, T, d) wil be set to 1 if kT ≤ t < (k + d)T and to 0 if (k + d)T ≤ t < (k + 1)T. The below is my script:
T = 2*pi;
d = 0.5;
syms v;
for t = [0:1:10]
v(t) = pwmmode (t,T,d);
end
plot (t,v);
function y = pwmmode (t,T,d)
k = 1;
if ((k*T <= t) & (t <= (k+d)*T)) y =1;
elseif (((k+d)*T <= t) & (t<(k+1)*T)) y=0;
else y = 2;
end
end
When I run my script above, I receive errors in the window. Below are the errors displayed on my window:

回答(1 个)

KSSV
KSSV 2021-1-28
In MATLAB arrays indices cannot be negative/ zeros. Your code:
for t = [0:1:10]
v(t) = pwmmode (t,T,d);
end
Should be like:
t = 0:1:10 ;
v = zeros(size(t)) ; % intialize accordingly
for i = 1:length(t)
v(i) = pwmmode (t(i),T,d);
end
  1 个评论
Walter Roberson
Walter Roberson 2021-1-28
Or in this particular case you could abbreviate to
for t = [0:1:10]
v(t+1) = pwmmode (t,T,d);
end
However, KSSV's suggstion of creating the list of values ahead of time and looping through indices is a more general approach that you should learn how to use. For example if you were to use
for t = [0:1/3:10]
v(3*t+1) = pwmmode (t,T,d);
end
then you would fail because the t values would not be exact multiples of 1/3

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by