# How do I use an matrix of indices to reference values in another matrix without using a loop?

1 Ansicht (letzte 30 Tage)
Joseph Koval am 14 Mär. 2018
Kommentiert: Joseph Koval am 14 Mär. 2018
I have a matrix that contains 20 vertical temperature values. It is of size 20 X 751 X 1500. Call this matrix alltemps.
I have another matrix that contains an index into the first dimension of the temperature. It is of size 1 X 751 X 1500. Call this matrix tempindex.
I want to create another 1 X 751 X 1500 matrix that is the temperature value from alltemps at the index pointed to by tempindex for all 751 X 1500 point in alltemps. Call this new matrix savedtemp
For example at 200 X 200, the temperature values in alltemps are:
280 282 284 286 288 290 292 294 296 298 300 302 304 306 308 310 312 314 316 318
And at 200 X 200, the (index) value in tempindex is 3.
So, the value in savedtemp would be 284 at 200 X 200 (i.e. the 3rd value in the temperature dimension of alltemps at 200 X 200.)
Is there a way to make a blanket (matrix-wise) assignment for every point in in the 751 X 1500 vector like this without having to run a loop?
##### 0 Kommentare-2 ältere Kommentare anzeigen-2 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

### Akzeptierte Antwort

Roger Stafford am 14 Mär. 2018
[a,b,c] = size(alltemps); % tempindex must be 1 x b x c
savedtemp = reshape(alltemps(reshape(tempindex,1,[])+(0:a:a*(b*c-1))),1,b,c);
##### 1 Kommentar-1 ältere Kommentare anzeigen-1 ältere Kommentare ausblenden
Joseph Koval am 14 Mär. 2018
Thanks Roger. Works like a charm!

Melden Sie sich an, um zu kommentieren.

### Kategorien

Mehr zu Resizing and Reshaping Matrices finden Sie in Help Center und File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by