Convert 1D array to 2D array with x and y coordinates supplied as individual vectors
7 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Himanish Basu
il 24 Nov 2015
Commentato: Jim Parsons
il 20 Ott 2017
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?
0 Commenti
Risposta accettata
Andrei Bobrov
il 24 Nov 2015
Data2D = accumarray([row(:),col(:)],data(:),[],[],nan);
5 Commenti
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
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 ?
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Matrix Indexing in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!