Filter löschen
Filter löschen

How to fix number of elements in for loop?

1 Ansicht (letzte 30 Tage)
Kelsea Miller
Kelsea Miller am 11 Dez. 2018
Kommentiert: Kelsea Miller am 11 Dez. 2018
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

Akzeptierte Antwort

GT
GT am 11 Dez. 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 Kommentare
Star Strider
Star Strider am 11 Dez. 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 am 11 Dez. 2018
Yes the for loop is redundant. Thanks for the assistance!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by