How to extract all values along the third axis of a 3d-array using a logical 2d-array?

20 views (last 30 days)
clear all; close all; clc
a = rand(10,10);
a(5,5) = 10;
b = rand(10,10,1000);
c = b(a == 10,:);
I have a 3d-array from which I would like to extract all values along the third dimension, that meet a specific criterion outlined by a 2d-array. The result would be a vector with a length of 1000 in this example.
Using the above code yields
"The logical indices in position 1 contain a true value outside of the array bounds."
Is there another way to combine the logical 2d-array with : for the third dimension?

Accepted Answer

Dyuman Joshi
Dyuman Joshi on 30 Nov 2023
Change the order of the dimension, and apply the logical indexing to the last two dimensions -
a = rand(10,10);
a(5,5) = 10
a = 10×10
0.8119 0.8021 0.6705 0.5890 0.7537 0.0864 0.3947 0.3684 0.5807 0.6421 0.5252 0.3511 0.6755 0.1485 0.4067 0.5524 0.9265 0.6145 0.6597 0.1955 0.4232 0.9698 0.9887 0.3227 0.7440 0.6890 0.6117 0.5431 0.4418 0.3064 0.1943 0.4909 0.1149 0.1278 0.5554 0.9638 0.5116 0.5799 0.8664 0.2565 0.2803 0.5091 0.4985 0.2506 10.0000 0.8735 0.8511 0.6460 0.5194 0.5078 0.4489 0.4585 0.7251 0.8376 0.1511 0.8815 0.3399 0.2441 0.5640 0.9755 0.8512 0.8669 0.4945 0.3113 0.1927 0.6766 0.1491 0.8641 0.9675 0.7919 0.2199 0.9170 0.1724 0.9808 0.4460 0.5060 0.3235 0.1395 0.3604 0.6461 0.9645 0.8171 0.1787 0.9012 0.0865 0.0329 0.4694 0.0011 0.9611 0.6206 0.1842 0.5321 0.8879 0.5550 0.0547 0.7905 0.9299 0.6325 0.3703 0.3298
b = rand(10,10,1000);
%Change the order of dimensions from [1 2 3] to [3 1 2]
B = permute(b, [3 1 2]);
%Logical indexing
C = B(:, a==10)
C = 1000×1
0.7216 0.2498 0.9391 0.7973 0.4856 0.3420 0.4636 0.5013 0.9975 0.7692
%% For checking the values
%Find the indices and use them to get the values
[row, col] = find(a==10);
c = squeeze(b(row, col, :))
c = 1000×1
0.7216 0.2498 0.9391 0.7973 0.4856 0.3420 0.4636 0.5013 0.9975 0.7692
%Comparison
isequal(C, c)
ans = logical
1
  4 Comments

Sign in to comment.

More Answers (1)

Matt J
Matt J on 30 Nov 2023
a = rand(10,10);
a(5,5) = 10;
b = a+rand(1,1,1000);
br=reshape(b,[],size(b,3));
c = br(a == 10,:)
c = 1×1000
10.4692 10.1143 10.9692 10.7970 10.0888 10.9303 10.2931 10.1473 10.3200 10.7804 10.3298 10.4334 10.3638 10.5040 10.8137 10.2234 10.4323 10.8027 10.0794 10.0928 10.0120 10.4608 10.6328 10.6812 10.3312 10.9594 10.9378 10.7513 10.6308 10.7608
  1 Comment
Stephen23
Stephen23 on 30 Nov 2023
Edited: Stephen23 on 30 Nov 2023
+1 while fiddling around with some different approaches I also came up with the same thing.
Note that the RESHAPE is quite fast compared to PERMUTE.

Sign in to comment.

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Tags

Products


Release

R2023a

Community Treasure Hunt

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

Start Hunting!