MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

# Using a Nested For Loop with input from an Array to Create an Array

Asked by Luke on 26 Apr 2013

Hello all,

I am trying to use the code seen below to output an array titled as "Fatigue_Life" when the function of "mancof" changes from positive to negative. The input of j should be for each variable in the "de" array and the output should be an array for the value of i at which the "mancof" function becomes negative. The output array should be the exact same dimension as the input array. For example, de(1,1)=0.00486 should result in Fatigue_Life(1,1)=72 and so on until the array has been fully calculated. The code currently runs but I can not seem to get the output matrix as described above it seems to just be taking the last value? I created the input array "de" of all the same values for simplicity so the output array should also be of the same value, known to be 72. I hope what I would like to happen is clear. Please see the code below, any help will be greatly appreciated.

MATLAB Code:

clc

clear

E=75657;

ef=.057429;

sf=227.365;

b=-0.0787879;

c=-0.6060601;

t=.00486;

de= t.*ones(1,100);

mancof=(sf/E*(2*i)^b)+(ef*(2*i)^c)-de;

Fatigue_Life=0;

for i=1:length(de)

```    for j=de(:,i)
if mancof>0
mancof=(sf/E*(2*i)^b)+(ef*(2*i)^c)-j;
Fatigue_Life=i
elseif mancof<0
fprintf('The Fatigue Life is: \n', Fatigue_Life)
end
end
end```

## Products

Answer by Andrei Bobrov on 26 Apr 2013
Edited by Andrei Bobrov on 26 Apr 2013
```ii = (1:100)';
mancof = sf/E*(2*ii).^b + ef*(2*ii).^c - t;
Fatigue_Life = find(mancof > 0);
```

```ii = (1:100)';
t = .00485 + .001*rand(30,1); % eg
```
```mancof = bsxfun(@gt, sf/E*(2*ii).^b + ef*(2*ii).^c, t(:)');
[i1,j1] = find(mancof);
Fatigue_Life = [i1,j1];
```

Luke on 26 Apr 2013

Hello Andrei,

I appreciate the response but this isn't exactly what I need because the variable "t" needs to be from an array that in the future will be of several different values. The input to the for loop should be for each variable of the array and then the result "Fatigue_Life" should be stored in an output matrix for each iteration.

Andrei Bobrov on 26 Apr 2013

Luke on 27 Apr 2013

Hello Andrei,

I finally got what I needed with the assistance of you, this seems to be a much simpler approach compared to the nested for loops. Below is the working code of yours that i slightly modified to get exactly what I needed. Thanks alot for all your help.

clc clear

E=75657;

ef=.057429;

sf=227.365;

b=-0.0787879;

c=-0.6060601;

de=[.00486, 0.004,0.0055,.003];

ii= (1:1:10000)'; % Number of cycles

mancof= bsxfun(@gt, sf/E*(2*ii).^b + ef*(2*ii).^c, de(:)');

[i1,j1]= find(mancof);

Fatigue= [i1,j1];

for i= 1:length(de)

Fatigue_Life(i)=find(mancof(:,i),1,'last');

end

Fatigue_Life