- Technical Services and Consulting
- Embedded Systems | Firmware Developement | Simulations
- Electrical and Electronics Engineering
How to replace elements in part of a matrix that meet a certain criteria?
27 views (last 30 days)
Show older comments
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.
0 Comments
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;
end
% 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
Feel free to contact me.
More Answers (0)
See Also
Categories
Find more on Platform and License 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!