How can I replace multiple indices of a matrix with specific values?
60 views (last 30 days)
I have a zero matrix B with dimensions 500x5000
I want to replace some elements with a specific value and other elements with another specidfic value.
lets say I want to replace indices 1,4 1,5 1,50 and 1,400. With a value 1
and 2,200 and 300,512 with value 1/sqrt(2).
While keeping the rest of the values as zeros
How can I do that in one line of code if possible and if not then whats the shortest way? As I do not want to enter each value seperatly using for example B(1,400) = 1.
Cris LaPierre on 18 Nov 2021
Edited: Cris LaPierre on 18 Nov 2021
Setting two separate values means two separate assignment commands. Since your values may not always be in the same row/column, I would use linear indexing.
linInd = sub2ind(size(B),[1 1 1 1],[4,5,50,400]);
B(linInd) = 1;
More Answers (1)
dpb on 18 Nov 2021
Edited: dpb on 18 Nov 2021
Build the indices vectors somehow -- you have to know where you want the values to in some manner, whether that is through some algorithm or an aribrary list. Then array indexing works to assign a constant to any list of locatiions.
You will have to iterate over the number of separate assignments to use a constant on the RHS of an assignment statement or build a commensurate vector of the proper length to match each set overall if insistent on the assignment in one line of code.
sub2ind and ind2sub can be helpful for these operations.