MATLAB Answers

How to change certain values in a 3 layer matrix and fill in another matrix?

8 views (last 30 days)
Hello everyone,
Newbie here. I have a 3 layer matrix that is defined as NDVI which has 7971 rows, 7851 columns, and 3 layers. I am working with blue, red, and green bands from satellite imagery. I want to replace each NDVI value greater than 0, and set it equal to the value of the green band. When NDVI is less than zero, set it equal to the blue band. I then want those replaced values, and the unreplaced values to fill in another matrix called NDVII with the same around of rows, columns, and layers.
Below is what I have so far. I have no experience writing a for loop on Matlab what-so-ever. Thanks for any help/advice.
for NDVII=7971:7851:3
if NDVI>0
else NDVI<0


Sign in to comment.

Accepted Answer

Elaine Famutimi Valdez
Elaine Famutimi Valdez on 27 Sep 2020
Edited: Elaine Famutimi Valdez on 27 Sep 2020
Here is the code in case anyone runs into this problem in the future:
[numRows, numCols] = size(NDVI); % matrix size
NDVII = zeros(numRows, numCols, 3); % zero filled array called NDVII with 3 layers
for j = 1:numCols % counter 'j' is going through each column
for i = 1:numRows % counter 'i' is going through each row
if NDVI(i, j) > 0
NDVII(i, j, :) = G(i, j); % ':' goes through all 3 layers
NDVII(i, j, 2) = 1; % makes it green
elseif NDVI(i, j) < 0
NDVII(i, j, :) = B(i, j);
NDVII(i, j, 3) = 1; % makes it blue


Sign in to comment.

More Answers (1)

KSSV on 21 Sep 2020
Let NDVI be your 7971*7851*3 matrix.
R = NDVI(:,:,1) ;
G = NDVI(:,:,2) ;
B = NDVI(:,:,3) ;
% replace values
% repalce each >0 value with Green values
R(R>0) = G(R>0) ;
B(B>0) = G(B>0) ;
% replace each < 0 value with Belue values
R(R<0) = B(R<0) ;
G(G<0) = B(G<0) ;
NDVI(:,:,1) = R ;
NDVI(:,:,2) = G ;
NDVI(:,:,3) = B ;


the cyclist
the cyclist on 21 Sep 2020
I think OP wanted a new variable, not to overwrite the old. So, instead of your last three lines, I would write:
NDVII = cat(3,R,G,B);

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!

Translated by