Replacing Values in Matrix with NaN's based on Row and Column

E
Emiliawilliams · Jul 20, 2020 · 1.9K views
Question
I hope all of you are well. I'm currently working on replacing specific element values with NaN's within a matrix that is 300x600. I want to replace the values based on pairs of rows and columns that I have previously identified. I'm unsure if I would use a for loop or if I would have to create a mask or if there is a simpler way of approaching the problem, but any help would be greatly appreciated! Thank you in advance! :)
Expert Answer
Profile picture of Kshitij Singh
Kshitij Singh PhD Expert
Answered Aug 12, 2026
matrix(ismember(matrix, [3,7,1])) = nan % an example of replacing numbers 3,7 & 9 with nans

% or
matrix = rand(5); % an example 
rows = [2, 5]; 
columns = [1, 4];
idx = rows + (columns - 1) * size(matrix, 1);
matrix(idx) = nan


% Sample input with some NaNs
A = rand(10);
A(randi([1 100],[20,1])) = NaN;
% Detect and replace NaNs
idx = isnan(A);
A(idx) = 0;
100% Run Guarantee 3-Hour Fast-Track Delivery

Need a Custom Version or Complete Simulation for This Problem?

Our 500+ PhD engineers build, debug, and optimize working MATLAB scripts and Simulink (.slx) models tailored to your exact assignment rubrics with zero plagiarism.

Tested on MATLAB R2024b / R2026a
Turnitin 0% Plagiarism Report
Free 7-Day Revisions Guarantee
Have a different question? Ask here

Get a Free Consultation or a Sample Assignment Review!