How can I save nested for loop results as a matrix?
Show older comments
so I am using a nested for loop to compute the result of an equation with multiple variables. my code is as follows (also I fairly new so if there's a better way to do this I am more than open)
p=50;
L=3;
E = 1.75*10^6 ; %lbf/in^2
I = 175 ; %in^4
eq1 = @(b,x) -((p.*b*x)./(6*L*E*I)).*(L^2 -b.^2 - x^2);
for b = linspace(0,L,4)
for x = linspace(0,L,4)
results = eq1(b,x)
end
end
what I want is a matrix where column one are the values of b column two are the values of x and column three are the values of results.
Thank you all!!
Answers (3)
No need for loops at all...
eq1 = @(b,x) -((p.*b.*x)./(6*L*E*I)).*(L^2 -b.^2 - x.^2); %<---modified
[B,X]=ndgrid(linspace(0,L,4));
output = [B(:),X(:), eq1(B(:),X(:))] ;
With Loop
p=50;
L=3;
E = 1.75*10^6 ; %lbf/in^2
I = 175 ; %in^4
eq1 = @(b,x) -((p.*b*x)./(6*L*E*I)).*(L^2 -b.^2 - x^2);
b = linspace(0,L,4) ;
x = linspace(0,L,4) ;
results = zeros(length(b),length(x)) ;
for i = 1:length(b)
for j = 1:length(x)
results(i,j) = eq1(b(i),x(j)) ;
end
end
Without Loop:
p=50;
L=3;
E = 1.75*10^6 ; %lbf/in^2
I = 175 ; %in^4
eq1 = @(b,x) -((p.*b*x)./(6*L*E*I)).*(L^2 -b.^2 - x^2);
b = linspace(0,L,4) ;
x = linspace(0,L,4) ;
[b,x] = meshgrid(b,x) ;
results = eq1(b,x) ;
Matt J
on 2 May 2019
[b,x]=deal(linspace(0,L,4));
output=nan(16,3);
for i=1:4
for j=1:4
row=sub2ind([4,4], i,j);
output(row,:) = [b(i),x(j), eq1(b(i),x(j)) ];
end
end
Categories
Find more on Loops and Conditional Statements 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!