How can I use a for loop to get the function to run at multiple values?
Show older comments
I am trying to use a for loop to get values for this equation: @(n,x) sqrt(2/4.0).*sin(((n.*pi).*(x-0.6))./4.0) for n = 1, 2, 3, 4
I also want to plot all four equations at n=1,2,3,4. I tried constructing a for loop, but get the error that the vectors are not the same length. I tried using linspace instead to remedy that but get the same error message. Please provide help.
n = linspace(1,1,4)
s = zeros(length (n),0)
for i = 1:length(n)
fxn = @(n,x) sqrt(2/4.0).*sin(((n.*pi).*(x-0.6))./4.0)
end
plot(n,s)
Answers (2)
David Hill
on 12 Mar 2021
n = 1:4;
x=0:.01:2*pi;
fxn = @(n) sqrt(.5)*sin(((n*pi)*(x-0.6))/4);
figure;
hold on;
for i = 1:length(n)
f(i,:) = fxn(n(i));
plot(x,f(i,:))
end
Star Strider
on 12 Mar 2021
I am not certain what result you want.
Try this:
fxn = @(n,x) sqrt(2/4.0).*sin(((n.*pi).*(x-0.6))./4.0);
n = (1:4).';
x = linspace(0, 2*pi, 100);
s = fxn(n,x);
figure
plot(n,s)
grid
xlabel('n')
ylabel('s')
Note that no loops are necessary, since the vectorised code creates the rows automatically.
Categories
Find more on MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!