How do I plot in a for loop?

조회 수: 12 (최근 30일)
Amy Jeffers
Amy Jeffers 2018년 1월 24일
답변: Walter Roberson 2018년 1월 24일
I am trying to plot y=A*(x+B)^n with constant A and B-values but I want to plot three different lines, each with a different n-value (n=1, 2, and 3). It keeps giving me a plot with one line and it also says there is an error using ".^". Can anybody tell me what's wrong with my code?
x = linspace(0, 2*pi, 100);
A = 1;
B = 1;
n = 1:3;
y = A*(x+B).^n;
for n = 1:3
plot(x,y); hold on
end
hold off

채택된 답변

Star Strider
Star Strider 2018년 1월 24일
Use the bsxfun function to automatically expand the vectors:
x = linspace(0, 2*pi, 100);
A = 1;
B = 1;
n = 1:3;
y = bsxfun(@power, A*(x+B), n');
for n = 1:3
plot(x,y); hold on
end
hold off
Note the transpose (') operator on ‘n’.

추가 답변 (1개)

Walter Roberson
Walter Roberson 2018년 1월 24일
[X, N] = ndgrid(x, n);
Y = A * (X + B).^N;
plot(X, Y)

카테고리

Help CenterFile Exchange에서 Scatter Plots에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by