How to fix number of elements in for loop?

1 次查看(过去 30 天)
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