# the variable appears to change size every loop iteration

1 view (last 30 days)
Nisreen Aljumaili on 30 Sep 2021
Answered: Image Analyst on 30 Sep 2021
%(a)Write the following script to plot the magnetization curve.
clc
clear
If = [0 0.5 1.0 1.5 2.0 2.5];
Ea = [0 75 150 205 242 270];
Ra = 0.14;
RI = 2;
la = 100;
Ifield = linspace(0,2.5,100);
for n = 1:100
Ea_curve(n) = spline(If,Ea,lfield(n));
end
plot(Ifield, Ea_curve)
title ('Field current vs. Generated EMF')
xlabel('Field current [A]')
ylabel('Generated EMF [V]')

Alan Stevens on 30 Sep 2021
You don't need the loop:
If = [0 0.5 1.0 1.5 2.0 2.5];
Ea = [0 75 150 205 242 270];
Ra = 0.14;
RI = 2;
la = 100;
Ifield = linspace(0,2.5,100);
Ea_curve = spline(If,Ea,Ifield);
plot(Ifield, Ea_curve)
title ('Field current vs. Generated EMF')
xlabel('Field current [A]')
ylabel('Generated EMF [V]')
##### 2 CommentsShowHide 1 older comment
Alan Stevens on 30 Sep 2021
If = [0 0.5 1.0 1.5 2.0 2.5];
Ea = [0 75 150 205 242 270];
Ra = 0.14;
RI = 2;
Ifield = linspace(0,2.5,100);
Ea_curve = spline(If, Ea, Ifield); % If not lf
la = Ea_curve/2;
Vt = Ea_curve-la*Ra;
Pload = Ea_curve.*la; % Notice the dot in .*
plot(Ifield, Vt)
title ('Field current vs. Terminal voltage')
xlabel('Field current [A]')
ylabel('Terminal voltage [V]')

Image Analyst on 30 Sep 2021
You're getting the warning because of this line
Ea_curve(n) = spline(If,Ea,lfield(n));
So every time you want to stuff a new number into the nth location of Ea_curve, it has to reallocation a new chunk of memory as big as the entire array, not just one 8 byte chunk for the additional element. To avoid the error you can preallocate Ea_curve with zeros before the loop
Ea_curve(n) = zeros(1, 100);
for n = 1 : 100

R2021a

### Community Treasure Hunt

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

Start Hunting!

Translated by