find linear indices 3D array in nested for loop
Show older comments
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)
Walter Roberson
on 29 Jan 2021
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
Iveth Romero
on 29 Jan 2021
Walter Roberson
on 29 Jan 2021
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
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!