Convert 1D array to 2D array with x and y coordinates supplied as individual vectors
6 views (last 30 days)
Show older comments
Himanish Basu
on 24 Nov 2015
Commented: Jim Parsons
on 20 Oct 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 Comments
Accepted Answer
Andrei Bobrov
on 24 Nov 2015
Data2D = accumarray([row(:),col(:)],data(:),[],[],nan);
5 Comments
Guillaume
on 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
on 20 Oct 2017
@Guillaume - instead of having it take the sum, is there something out there that'll get it to take the average ?
More Answers (0)
See Also
Categories
Find more on Matrix Indexing 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!