Multiple outputs from a for loop
3 views (last 30 days)
Show older comments
Basic problem, but I can't find the solution:
consider basic a for loop:
for i = 1:5
z(i)=3*i
end
It produces a vector z= [3 6 9 12 15]. What I need is all the components of the vector z as a sperate variables(scalars), let,s say
z1=3, z2=6 and so on. How can I do that?
Thanks in advance
Roger Kalvig
Accepted Answer
Stephen23
on 21 Jun 2022
Edited: Stephen23
on 21 Jun 2022
Rather than distracting with anti-pattern numbered variables (like you asked about), instead you should just use basic, normal, efficient, easy, simple, standard indexing. Indexing is how MATLAB works best.
d = 5;
xc = -100:10:280; % (some range suiting fcn function)
iv = nan(1,numel(xc));
fh = @(x) fcn(x) .* myGausstest(x);
for k = 1:numel(xc)
% do integration here of the product of both functions fcn*myGausstest for integral limts (xc-d,xc+d)" using trapz or integral
iv(k) = integral(fh,xc(k)-d,xc(k)+d);
end
plot(xc,iv)
function y = fcn(x)
Bext = 0.6;
G = 10.553;
y = 1./(G.*Bext.*sind(x));
y(x<0) = 0;
y(x==0) = 100;
y(x==180) = 100;
y(x>180) = 0;
end
function y = myGausstest(x)
A = 10;
w = 20;
xc = 90;
y = A.*exp(-0.5*((x-xc)./w).^2);
end
3 Comments
Stephen23
on 21 Jun 2022
Edited: Stephen23
on 21 Jun 2022
"One problem i can see is I already defined xc within"
Presumably you only intend the xc inside the function to refer to a single value, not the entire vector, in which case you can easily pass the value by parameterizing the function:
For example:
d = 5;
xc = -100:10:280; % (some range suiting fcn function)
iv = nan(1,numel(xc));
for k = 1:numel(xc)
fh = @(x) fcn(x) .* myGausstest(x,xc(k)); % parameterize function
iv(k) = integral(fh,xc(k)-d,xc(k)+d);
end
plot(xc,iv)
function y = fcn(x)
Bext = 0.6;
G = 10.553;
y = 1./(G.*Bext.*sind(x));
y(x<0) = 0;
y(x==0) = 100;
y(x==180) = 100;
y(x>180) = 0;
end
function y = myGausstest(x,xc)
A = 10;
w = 20;
y = A.*exp(-0.5*((x-xc)./w).^2);
end
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!