Eliminating nested loops without repeating input combinations for equation output
11 views (last 30 days)
I have been given an equation with several variables. For each variable I have created a normal distribution using normn. I would like to get all the solutions to the equation using every single possible combination of values without them repeating themselves. Since I want to use distribution fitter and fit a norma distribution to the data, having inputs repeat themselves would not be good. Currently I am using nested for loops but this is very inefficient especially as I start adding variables. does anybody know of a way in which I can speed up my code?
When n gets to be higher than 10 it becomes unbearably slow. I would like n to be at least 500.
t_mean = 9.74; %mm
D_mean = 324; %mm
dm_mean = 3.896; %mm
sig_u_mean = 542; %MPa
l_mean = 528; %mm
%range of values and number of random inputs
n = 100;
t = 0.01*randn(1, n) + t_mean;
D = 0.25*randn(1, n) + D_mean;
sig_u = 0.25*randn(1, n) + sig_u_mean;
dm = 0.001*randn(1, 100) + dm_mean;
l = 0.25*randn(1, 100) + l_mean;
%initialize the Pb matrix
K = zeros(1,1000);
m = 1;
%loop over all possible input combinations
for i = 1 : length(t)
for j = 1 : length(D)
for k = 1 : length(sig_u)
for n = 1 : length(dm)
for o = 1 : length(l)
M = sqrt(1 + 0.31*(l_mean/sqrt(D(j)*t(i)))^2);
K(m) = ((2*t(i))/(D(j)-t(i)))*sig_u(k)*abs((1-(dm_mean/t(i)))/(1-(dm_mean/(t(i)*M))));
m = m+1;
Swetha Polemoni on 2 Sep 2020
Eliminating nested for loops is possible using “ndgrid()” function. Look into the following code snippet for better understanding.
for i= 1:10
Here out1 and out2 gives same output. Atleast 2 nested loops can be eliminated using this function.