how to plot a vector

조회 수: 17 (최근 30일)
Elinor Ginzburg
Elinor Ginzburg 2020년 5월 24일
답변: Elinor Ginzburg 2020년 5월 24일
hello,
I'm trying to plot the points of a vector to see if it looks like I want it to, but I get a blank figure. can anyone please advice me on what's wrong with my code?
% units %
lambda = 1; L = 10; N = 500; a = 1; V0 = 5;
% Create lattice points %
dx = L/N;
x = zeros([1 N]);
for n = 1:N
x(n) = -L/2+(n-0.5)*dx;
end
% define potential %
Vho = zeros([1 N]);
for i = 1:N
Vsw = -V0*(heaviside(x(i)+a/2)-heaviside(x(i)-a/2));
end
figure
plot(Vsw)
Thank you very much for your help!
  댓글 수: 1
Stephen23
Stephen23 2020년 5월 24일
Given that heaviside belongs to the Symbolic Toolbox, you will probably need to consider it a bit more carefully.

댓글을 달려면 로그인하십시오.

채택된 답변

Stephen23
Stephen23 2020년 5월 24일
편집: Stephen23 2020년 5월 24일
"what's wrong with my code?"
  • you preallocate a variable named Vho which you never use again.
  • inside the loop you allocate to a variable named Vso , but you do not use any indexing, so on each loop iteration you simply overwrite Vso, thus leaving only the (scalar value) from the final iteration.
So even though you write that you are plotting a vector, if you actually take a look at Vso it is actually scalar (and plotting a scalar gives the appearance of an empty plot, although it isn't actually, just the default linespec does not include any point marker).
I fixed those mistakes (and replaced heaviside with a simple logical comparison):
Vsw = zeros(1,N);
for k = 1:N
Vsw(k) = -V0*((x(k)+a/2)>0 - (x(k)-a/2)>0);
end
plot(Vsw,'-*')

추가 답변 (2개)

Tommy
Tommy 2020년 5월 24일
Vsw is a scalar, so nothing will show when you plot it. You are overwriting the value of Vsw in each loop of your for loop. Do you mean to instead store the values within Vho and plot that?
% define potential %
Vho = zeros([1 N]);
for i = 1:N
Vho(i) = -V0*(heaviside(x(i)+a/2)-heaviside(x(i)-a/2));
end
figure
plot(Vho)

Elinor Ginzburg
Elinor Ginzburg 2020년 5월 24일
Thank you very much guys!
I mistyped and didn't index Vsw as you all mentioned.

카테고리

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

태그

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by