How to insert values to specific locations in a matrix

12 visualizzazioni (ultimi 30 giorni)
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!

Risposta accettata

Andrei Bobrov
Andrei Bobrov il 1 Giu 2017
Modificato: Andrei Bobrov il 1 Giu 2017
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 Commenti
Amay Gupta
Amay Gupta il 14 Ott 2020
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?

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Matrices and Arrays 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!

Translated by