I'm trying to plot a graph with if than statements but keep getting the error "Array indices must be positive integers or logical values."

29 次查看(过去 30 天)
function x= HW2Problem1(y)
x=1:.001:10;
n=length(x);
for i=(0:n)
if x(i)==0
y(i)=16.67;
elseif 0<x(i) & x(i)<5
y(i)=2*x(i);
elseif x(i)==5
y(i)=-91.67;
else
y(i)=10;
end
end
plot(x,y)

采纳的回答

Star Strider
Star Strider 2025-2-26
The definition of ‘positive integer’ are integers greater than zero.
So use:
for i=(1:n)
instead of:
for i=(0:n)
There are still problems, however your funciton no longer throws that error. (It also needs an additional end that I provided.)
y = sort(randn(1,25))
y = 1×25
-1.7365 -1.6373 -1.0383 -1.0108 -0.7728 -0.7171 -0.6049 -0.5756 -0.4811 -0.3221 -0.2715 -0.2055 -0.1518 0.0962 0.2126 0.2960 0.4398 0.5070 0.5795 0.6963 0.7709 0.8138 1.0215 1.3392 1.9744
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
x = HW2Problem1(y)
x = 1×9001
1.0000 1.0010 1.0020 1.0030 1.0040 1.0050 1.0060 1.0070 1.0080 1.0090 1.0100 1.0110 1.0120 1.0130 1.0140 1.0150 1.0160 1.0170 1.0180 1.0190 1.0200 1.0210 1.0220 1.0230 1.0240 1.0250 1.0260 1.0270 1.0280 1.0290
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
plot(x,y)
Error using plot
Specify the coordinates as vectors or matrices of the same size, or as a vector and a matrix that share the same length in at least one dimension.
function x= HW2Problem1(y)
x=1:.001:10;
n=length(x);
for i=(1:n)
if x(i)==0
y(i)=16.67;
elseif 0<x(i) & x(i)<5
y(i)=2*x(i);
elseif x(i)==5
y(i)=-91.67;
else
y(i)=10;
end
end
end
I leave the rest to you.
.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

产品


版本

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by