How to fix number of elements in for loop?

조회 수: 2 (최근 30일)
Kelsea Miller
Kelsea Miller 2018년 12월 11일
댓글: Kelsea Miller 2018년 12월 11일
Hi,
I have the following for loop I'm trying to create and plot the resulting equation over the range -6<a<6. However the way it is currently set up, the numbe rof elements on LHS and RHS do not equal. Any suggestions?
q= 0.2;
E = 200*10^8;
a= -6:6;
n=numel(a);
v=zeros(1,n);
for k=1:n
v(k)= ((-2*q)/pi*E)*(2.*a.*log(a)
end

채택된 답변

Gareth
Gareth 2018년 12월 11일
There are couple of things here however the first is to get your code working:
q= 0.2;
E = 200*10^8;
a= -6:6;
n=numel(a);
v=zeros(1,n);
for k=1:n
v(k,:)= ((-2*q)/pi*E)*(2.*a.*log(a))
end
Notice that you were missing a bracket at the end of log(a)) and that the answer is actually an array, so when attributing the values of an array to a single place MATLAB errors, hence the v(k,:) meaning for row k, fill out all the values.
That being said I am not sure if this is what you want as you are repeating the values in each row, the for loop really does not make much sense as is. One could simply do:
q= 0.2;
E = 200*10^8;
a= -6:6;
n=numel(a);
v=zeros(1,n);
v= ((-2*q)/pi*E)*(2.*a.*log(a))
And if you want to plot v, then a simple
plot(v)
I hope that this helps.
  댓글 수: 2
Star Strider
Star Strider 2018년 12월 11일
To use the loop as I believe you intend, your need to index ‘a’ as ‘a(k)’:
for k=1:n
v(k)= ((-2*q)/pi*E)*(2.*a(k).*log(a(k)));
end
GK’s second version (without the loop) is the most efficient.
Kelsea Miller
Kelsea Miller 2018년 12월 11일
Yes the for loop is redundant. Thanks for the assistance!

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by