MATLAB Answers

Extracting a value from a 3D table

1 view (last 30 days)
Jerry Smith
Jerry Smith on 23 Nov 2019
Answered: Les Beckham on 23 Nov 2019
So Inf or Nan were in the first row, column ... then the code would output (1,1,1).

Accepted Answer

Stijn Haenen
Stijn Haenen on 23 Nov 2019
Maybe this works, for output(a,b,c):
Num_nan=find(isnan(Table));
c=floor(Num_nan/(81*81))+1;
b=floor(rem(Num_nan,81*81)/81)+1;
a=rem(rem(Num_nan,81*81),81);
  1 Comment
Jerry Smith
Jerry Smith on 23 Nov 2019
This works thank you but I dont really understand the code, is there a chance you could explain it?

Sign in to comment.

More Answers (2)

Stijn Haenen
Stijn Haenen on 23 Nov 2019
Sure,
In the first line "Num_nan=find(isnan(Table));" you get the positions of the NaN, but this is just a number. For example, applying this on the following matrix:
[1 2 3;
4 NaN 6;
7 8 9]
Num_nan = 5
But then you should use this number to get the row and column and this is done with the other lines.
There are 3 numbers in one column, so
floor(Num_nan/3)+1=2;
So the column number is 2,
for the row we use the remaining of 5/3 which is 2
so NaN is at (2,2).

Les Beckham
Les Beckham on 23 Nov 2019
A 3d example using Matlab's indexing functions instead of floor and rem:
t3=[1 2 NaN;
4 5 6;
7 8 9]; % a 2d matrix with one NaN
t3(:,:,2) = t3'; % add another dimension using the transpose of the first 'page'
idx = find(isnan(t3)); % find the linear indices of the NaNs in the 3d array
[r, c, p] = ind2sub(size(t3), find(isnan(t3))); % convert the linear indices to array indices
% print out the results
fprintf('r\t\c\tp\n');
for (i = 1:length(r))
fprintf('%d\t%d\t%d\n', r(i), c(i), p(i));
end
The find() function returns the linear indices (see Array Indexing) of the NaNs. The ind2sub() function converts those to row, column, and 'page' indices.
The size() function determines the dimensions of the input array so that you don't have to hard code them.
Note that this approach can be extended to more than three dimensions as well (see the documentation for ind2sub).

Community Treasure Hunt

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

Start Hunting!