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

Illustration
Ariah - 2020-09-28T11:28:07+00:00
Question: How to change certain values in a 3 layer matrix and fill in another matrix?

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.     NDVII=zeros(7971,7851,3); for NDVII=7971:7851:3 NDVI=NDVII; if NDVI>0 G=NDVII; else NDVI<0 B=abs(NDVII); end end imagesc(NDVII)

Expert Answer

Profile picture of Kshitij Singh Kshitij Singh answered . 2025-11-20

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
         end
     end
 end


Not satisfied with the answer ?? ASK NOW

Get a Free Consultation or a Sample Assignment Review!