# Max of vector in higher dimensional array subject to constraints

6 views (last 30 days)
James Lee on 18 Feb 2020
Commented: Matt J on 19 Feb 2020
Hello all,
I currently have code that's working but inefficient due to nested for loops, and I would like to vectorize it as possible. My data set is a higher dimensional array (a,b,.....z), and I'd like to find the maximum of each vector of z subject to a constraint based on the values of the other vectors.
For example, take a 3 dimensional array (a,b,c). I will have calculated a matrix (a x b-sized) of a constraint. I'd like to find a (a x b-sized) matrix that gives the maximum of each c vector that is measured only on the domain of (constraint:end). Let me know if there is a way to do this without for loops.
(edited for clarity)

Matt J on 18 Feb 2020
Edited: Matt J on 18 Feb 2020
N=ndims(A); %A is the given matrix
z=size(A,N);
idx=reshape(1:z, [ones(1,N-1),z] ) < constraint; %requires R2016b or higher
B=A;
B(idx)=-inf;
result=max(B,[],N);

James Lee on 19 Feb 2020
Hey Matt,
This worked. I had to modify it a bit because I realized I had made a small mistake in the prompt (the constraint was an index to the matrix as opposed to a value) but this approach helped a lot. I appreciate it!
Matt J on 19 Feb 2020
My solution did assume that constraint is a matrix of indices. So, I'm not sure why you had to change anything. Glad you got what you need, though.

darova on 18 Feb 2020
Use max()
B = max(A,[],3);

R2018a

### Community Treasure Hunt

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

Start Hunting!