필터 지우기
필터 지우기

How to insert values to specific locations in a matrix

조회 수: 4 (최근 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 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