How can I replace multiple indices of a matrix with specific values?
40 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
采纳的回答
Cris LaPierre
2021-11-18
编辑:Cris LaPierre
2021-11-18
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.
B=zeros(500,5000);
linInd = sub2ind(size(B),[1 1 1 1],[4,5,50,400]);
B(linInd) = 1;
sum(B,'all')
0 个评论
更多回答(1 个)
dpb
2021-11-18
编辑:dpb
2021-11-18
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!