find linear indices 3D array in nested for loop

Hi,
I want to find the linear indices of a 3D array (tbn_new) that is formed using a nested FOR loop, the indices should correspond to the values equal to the elements of the vector tbn_exp. In every step through the loop, I want to obtain the indices corresponding to the values in the corresponding column (j) and page (i) of tbn_new to later calculate another variable using only the matching values, but I have 2 issues:
  • When using the function find it does not return all the indices corresponding to the first page of the 3D array.
  • I want to have the indices of the entire 3D array, but I obtain only the values of the first page (and incomplete, as mentioned above).
The code is the following:
k = [1 2];
K = [1 2 3];
m = length(K);
n = length(k);
tbn_exp = [0 0.5 0.7];
ybn_exp = [0.9 1.2 1.3];
tmax=1;
y0=0.1;
dt=0.1;
h=0;
for i = 1:m
for j = 1:n
yb=y0;
[ybn,tbn] = Euler(dt,yb,tmax,h,k(j),K(i));
ybn_new(:,j,i)=ybn;
tbn_new(:,j,i)=tbn;
% find indices of tbn_exp in tbn_new
nn = find(ismember(tbn_new(:,j,i),tbn_exp));
end
end
The function Euler is the following:
function [ybn,tbn] = Euler(dt,yb,tmax,h,k,K)
for tb=0:dt:tmax
ybnew=yb+dt*k*(yb-tb^2*K);
yb=ybnew;
h=h+1;
ybn(h)=yb;
tbn(h)=tb;
end
end
In other words, I want to obtain the indices: 1 6 8 in the first step through the loop, then the indices 12 17 19 in the second step, 23 28 30 in the third step, and so on.

Answers (1)

nn = find(ismember(tbn_new(:,j,i),tbn_exp));
nn3d = nn + (j-1)*n + (i-1)*n*m;
%now save them or compute with them or whatever
And you should pre-allocate tbn_new for efficiency.

2 Comments

Hi Walter, thank you for your answer. I included the line you suggested (nn3d) but I am still not getting what I am looking for. I want to obtain the indices: [1 6 8] in the first step through the loop, then the indices [12 17 19] in the second step through the loop, [23 28 30] in the third step, and so on. These indices correspond to the elements of tbn_new equal to the values of tbn_exp.
I am still obtaining only two indices in each step of the loop when there should be 3 indices. Also, the values are not correct. They do not correspond to the indices I am looking for.
I hope my question is clear, or should I reformulate it?
You are using ismember() to compare floating point numbers that have been calculated in different ways. You should not be expecting any matches. http://matlab.wikia.com/wiki/FAQ#Why_is_0.3_-_0.2_-_0.1_.28or_similar.29_not_equal_to_zero.3F

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 29 Jan 2021

Commented:

on 29 Jan 2021

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!