Convert 1D array to 2D array with x and y coordinates supplied as individual vectors

7 visualizzazioni (ultimi 30 giorni)
Hi, I have 3 vectors: row=[1,3,2,2]; col=[2,1,2,1]; data=[1.8, 2.5, 3.9, 4.2]; I need to index the data into a 2D array using the row and column vectors stating the coordinates (with NaNs where I dont have any values) such that I get as my final answer as :
data2D =
[ NaN 1.8000
4.2000 3.9000
2.5000 NaN]
The code that I am using now is as follows:
Data2D = nan(max(row),max(col));
for i =1:length (row);
Data2D (row(i),col(i))= data(i); % Genarating Data Matrix %
end
However, I am dealing with very large data sets and the for loop is proving to be quite slow. Is there anyway I can directly index the data with the row and col vectors without a for loop?

Risposta accettata

Andrei Bobrov
Andrei Bobrov il 24 Nov 2015
Data2D = accumarray([row(:),col(:)],data(:),[],[],nan);
  5 Commenti
Guillaume
Guillaume il 25 Nov 2015
It can't really be done with accumaray, but it can be done with sub2ind:
c = cell(max(row), max(col));
c(sub2ind([max(row) max(col)], row, col) = data;
Note that sub2ind will also work with numerical matrices.
Jim Parsons
Jim Parsons il 20 Ott 2017
@Guillaume - instead of having it take the sum, is there something out there that'll get it to take the average ?

Accedi per commentare.

Più risposte (0)

Community Treasure Hunt

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

Start Hunting!

Translated by