How to extract all values along the third axis of a 3d-array using a logical 2d-array?
20 views (last 30 days)
Show older comments
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?
0 Comments
Accepted Answer
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
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)
%% For checking the values
%Find the indices and use them to get the values
[row, col] = find(a==10);
c = squeeze(b(row, col, :))
%Comparison
isequal(C, c)
4 Comments
More Answers (1)
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,:)
1 Comment
See Also
Categories
Find more on Creating and Concatenating Matrices 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!