Clear Filters
Clear Filters

How to fix number of elements in for loop?

1 view (last 30 days)
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

Accepted Answer

GT
GT on 11 Dec 2018
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 Comments
Star Strider
Star Strider on 11 Dec 2018
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 on 11 Dec 2018
Yes the for loop is redundant. Thanks for the assistance!

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!