How to fix number of elements in for loop?
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Kelsea Miller
el 11 de Dic. de 2018
Comentada: Kelsea Miller
el 11 de Dic. de 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
0 comentarios
Respuesta aceptada
Gareth
el 11 de Dic. de 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 comentarios
Star Strider
el 11 de Dic. de 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.
Más respuestas (0)
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!