How to insert values to specific locations in a matrix

4 次查看(过去 30 天)
Hi,
Looking for help on how to insert values into a 3D matrix (array) based on their latitude and longitude positions. This is an example of what I need to do...
% Mx and My provides the background info for longitude and latitude:
lon=-145:0.1:-144;
lat=45:0.1:46;
[Mx, My] = meshgrid(lon, lat);
% aa and bb are the specific location (longitude and latitude, respectively) for values in cc
% Here cc size is 2 x 6, meaning I have 2 set of values to insert in a 3D array.
aa=[-144.9 -144.8 -144.6 -144.5 -144.3 -144.2];
bb=[45.0 45.1 45.6 45.7 45.9 46.0];
cc=[10 23 3 5 9 6; 21 56 14 63 84 98];
% pre-allocating memory for matrix_final (11 x 11 x 2), meaning I have a 3D array with 2 layers.
matrix_final=nan(11,11,2);
% Here is where I need help to insert the values from cc at specific aa and bb locations into matrix_final, at each layer.
My data has 4000 layers, instead of 2 here in the example. So being able to make this work in a loop would be very appreciated, thank you!

采纳的回答

Andrei Bobrov
Andrei Bobrov 2017-6-1
编辑:Andrei Bobrov 2017-6-1
lon=-145:0.1:-144;
lat=45:0.1:46;
aa=[-144.9 -144.8 -144.6 -144.5 -144.3 -144.2];
bb=[45.0 45.1 45.6 45.7 45.9 46.0];
cc=[10 23 3 5 9 6; 21 56 14 63 84 98];
[~,ix] = ismember(aa,lon);
[~,iy] = ismember(bb,lat);
s = size(cc,1);
out = nan([numel(lon),numel(lat),s]);
out(sub2ind(size(out),repmat(ix,1,s),...
repmat(iy,1,s),repelem(1:size(cc,1),numel(aa)))) = cc';
other variant with griddedInterpolant
m = numel(lon);
l = size(cc,1);
[ii,jj] = ndgrid(lon,lat);
k = numel(ii);
F = griddedInterpolant(ii,jj,reshape(1:k,m,[]),'nearest','nearest');
out = nan(m,numel(lat),l);
out(bsxfun(@plus,F(aa(:),bb(:)),k*(0:l-1))) = cc';
  2 个评论
Amay Gupta
Amay Gupta 2020-10-14
what if, i have a 2d matrix of size 3000 by 3000 and i have to insert a row and coresponding column in a matrix at lets say 582 position?

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by