Clear Filters
Clear Filters

How to replace elements in part of a matrix that meet a certain criteria?

14 views (last 30 days)
I want to replace elements in certain rows and columns with 0, if they are greater or less than 0. As I am using a sparse matrix (that's 10 000 x 10 000) I don't think I can just set those rows equal to zero, so I am specifically looking for all nonzero elements and replacing them. I can do this row by row in a for loop over i: A( rows(i) , abs(A(rows(i),:))>0 )=0, if rows is a 1D array with row indices. I was wondering if there is a way to do this for the whole matrix without looping? I tried A( rows , abs(A(rows,:))>0 )=0, but that doesn't work as my logical array is 2D.

Accepted Answer

Hassaan on 21 Mar 2024
Edited: Hassaan on 21 Mar 2024
% Assuming A is your sparse matrix and 'rows' is the 1D array of row indices you're interested in
[rowIdx, colIdx, values] = find(A);
% Initialize a logical vector to mark elements to change
toChange = false(size(values));
% Loop through the specific rows you're interested in
for i = 1:length(rows)
% Find indices in rowIdx that match the current row of interest
inRow = rowIdx == rows(i);
% Mark these for change (you can adjust this condition as needed)
toChange(inRow) = abs(values(inRow)) > 0;
% Now, toChange contains true for elements to be set to zero
% Replace values to be changed with 0
values(toChange) = 0;
% Create the new sparse matrix
A_new = sparse(rowIdx, colIdx, values, size(A,1), size(A,2));
If you find the solution helpful and it resolves your issue, it would be greatly appreciated if you could accept the answer. Also, leaving an upvote and a comment are also wonderful ways to provide feedback.
It's important to note that the advice and code are based on limited information and meant for educational purposes. Users should verify and adapt the code to their specific needs, ensuring compatibility and adherence to ethical standards.
Professional Interests
  • Technical Services and Consulting
  • Embedded Systems | Firmware Developement | Simulations
  • Electrical and Electronics Engineering
Feel free to contact me.
  1 Comment
Sobhan on 21 Mar 2024
This is similar to what I did, but my question was more specificly if there is a way to do it without looping.
My original solution was:
bottomD = [3,5,7]; %example
K = rand(10,10); %example (although it's sparse)
for i = 1:length(bottomD)
I figured out that K(bottomD,:)=sparse(length(bottomD),10) works as I don't care about the values in those rows, so I can just replace the entire rows.

Sign in to comment.

More Answers (0)


Find more on Loops and Conditional Statements in Help Center and File Exchange





Community Treasure Hunt

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

Start Hunting!