Filter löschen
Filter löschen

How can I replace multiple indices of a matrix with specific values?

5 Ansichten (letzte 30 Tage)
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.

Akzeptierte Antwort

Cris LaPierre
Cris LaPierre am 18 Nov. 2021
Bearbeitet: Cris LaPierre am 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.
B=zeros(500,5000);
linInd = sub2ind(size(B),[1 1 1 1],[4,5,50,400]);
B(linInd) = 1;
sum(B,'all')
ans = 4

Weitere Antworten (1)

dpb
dpb am 18 Nov. 2021
Bearbeitet: dpb am 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.

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Tags

Produkte


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by