# extract data from a loop

26 views (last 30 days)
Oday Shahadh on 4 Jun 2020
Hi Guys,
Can any body help on how extract and plot data from this?
clc
clear
close all
format long
mu0=4*pi*10^-7;
R=0.9;
N=17;
I=12.5;
for z=-1.5:0.01:1.5;
B1=((mu0*N*I*R^2)/2)*(1/(R^2+(z+(R/2))^2)^(3/2));
B2=((mu0*N*I*R^2)/2)*(1/(R^2+(z-(R/2))^2)^(3/2));
Bt=B1+B2;
figure(1)
plot(z,B1); hold on;grid on
plot(z,B2); hold on;grid on
plot(z,Bt); hold on;grid on
end

Shubhankar Poundrik on 5 Jun 2020
Hi Oday,
I understand that you are finding difficulty in keeping each value of the variables generated in the loop saved. Additionally, the plot generated by your code is blank and does not show the plots.
Data created in a loop can be extracted by saving it to an array. The entire data can then be plotted from the array itself, rather than plotting it point wise in the loop. The hold on command may be used once before adding all the plots. Then the hold off command should be used.
The below code may help.
clc
clear
close all
format long
mu0=4*pi*10^-7;
R=0.9;
N=17;
I=12.5;
z2 = -1.5:0.01:1.5;
elm = length(z2);
B1arr = zeros(1, elm); % creating array to add B1 to in the loop
B2arr = zeros(1, elm); % creating array to add B2 to in the loop
Btarr = zeros(1, elm); % creating array to add Bt to in the loop
i=1;
for z=-1.5:0.01:1.5
B1=((mu0*N*I*R^2)/2)*(1/(R^2+(z+(R/2))^2)^(3/2));
B2=((mu0*N*I*R^2)/2)*(1/(R^2+(z-(R/2))^2)^(3/2));
Bt=B1+B2;
B1arr(1,i ) = B1; % adding B1 to array
B2arr(1,i ) = B2; % adding B2 to array
Btarr(1,i ) = Bt; % adding Bt to array
i=i+1;
end
hold on
plot(z2, B1arr, 'b')
plot(z2, B2arr, 'r')
plot(z2, Btarr, 'g')
hold off
Regards,
Shubhankar

KSSV on 5 Jun 2020
Edited: KSSV on 5 Jun 2020
clc
clear
close all
format long
mu0=4*pi*10^-7;
R=0.9;
N=17;
I=12.5;
Z=-1.5:0.01:1.5;
B1 = zeros(size(Z)) ;
B2 = zeros(size(Z)) ;
for i = 1:length(Z)
z = Z(i) ;
B1(i)=((mu0*N*I*R^2)/2)*(1/(R^2+(z+(R/2))^2)^(3/2));
B2(i)=((mu0*N*I*R^2)/2)*(1/(R^2+(z-(R/2))^2)^(3/2));
end
Bt = B1+B2 ;
figure
hold on
plot(Z,B1,'r')
plot(Z,B2,'b')
plot(Z,Bt,'g')
Note that, there is no requirement of using a loop. You can achieve what you want without loop also.
clc
clear
close all
format long
mu0=4*pi*10^-7;
R=0.9;
N=17;
I=12.5;
z=-1.5:0.01:1.5;
B1=((mu0*N*I*R^2)/2)*(1./(R^2+(z+(R/2)).^2).^(3/2));
B2=((mu0*N*I*R^2)/2)*(1./(R^2+(z-(R/2)).^2).^(3/2));
Bt = B1+B2 ;
figure
hold on
plot(z,B1,'r')
plot(z,B2,'b')
plot(z,Bt,'g')

madhan ravi on 5 Jun 2020
KSSV on 5 Jun 2020
What do you think?
madhan ravi on 5 Jun 2020
xD

madhan ravi on 5 Jun 2020
Edited: madhan ravi on 5 Jun 2020
No loops needed:
mu0=4*pi*10^-7;
R=0.9;
N=17;
I=12.5;
z=-1.5:0.01:1.5;
B1=((mu0*N*I*R^2)/2).*(1./(R^2+(z+(R/2)).^2).^(3/2));
B2=((mu0*N*I*R^2)/2).*(1./(R^2+(z-(R/2)).^2).^(3/2));
Bt=B1+B2;
figure(1)
plot(z,B1,'k')
hold on
grid on
plot(z,B2,'b')
plot(z,Bt,'m')

Oday Shahadh on 5 Jun 2020
Hi Guys,
Is there any way to accept all your answers? you all great, really appreciated