How to insert values to specific locations in a matrix

12 ビュー (過去 30 日間)
Robert
Robert 2017 年 6 月 1 日
コメント済み: Amay Gupta 2020 年 10 月 14 日
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 件のコメント
Robert
Robert 2017 年 6 月 1 日
Thank you so much Andrei!
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 Center および File ExchangeMatrices and Arrays についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by