Replace certain Values within a Matrix Based on Indices from Another matrix

49 Ansichten (letzte 30 Tage)
Hello I have two matrices of size 24x365.
gridsupplyidx has somevalues
gridsupply is a matrix of zeros size 24x365
I would like to replace the zero in gridsupply with a 5 at the position mentioned in gridsupply idx
For example if the first value of the first row of gridsupplyidx is 7 then the value at gridsupply(7,1) should be replaced by 5
This is what I tried but it does not work. thank you for the help
gridsupplyidx=index.*((1:24)<=dailygridhours)';
gridsupply=zeros(size(index));
ind=gridsupplyidx ~=0;
newindex=setdiff(1:numel(gridsupply),ind);
gridsupply=gridsupply.*ind;
  2 Kommentare
Aditya Ramesh
Aditya Ramesh am 22 Mär. 2022
Hey Ritika,
From your question above, I understand that the '7' in the first cell of gridsupplyidx is 7, and hence the value changed in grid supply is in the 7th column, but from where are you referencing the '1' from (1,7)? Is it because its in the first row or first column?
Can you give me an example of what you want in gridsupply if gridsupplyidx(5,10)=23 (just a random index to understand)?
Ritika Srinivasan
Ritika Srinivasan am 22 Mär. 2022
Hey aditya thank you for the reply , you are right the first value of gridsupplyidx is 7 and so the value in the first column and 7th row of gridsupply should be 5.
so in your example if gridsupplyidx(5,10)=23 then I would like (23,10)=5.
I hope this makes sense

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Matt J
Matt J am 22 Mär. 2022
[~,J,I]=find(gridsupplyidx);
idx=sub2ind(size(gridsupply),I,J);
gridsupply(idx)=5;

Weitere Antworten (1)

Aditya Ramesh
Aditya Ramesh am 22 Mär. 2022
Bearbeitet: Aditya Ramesh am 22 Mär. 2022
% Creating two zero matricss
X1 = zeros(5);
X2 = zeros(5);
% Introducing non zero values in the first one
X1(3,5) = 1;
X1(2,2) = 4;
X1(4,3) = 2;
X1(4,1) = 3;
% finding non zero indices
[rows,cols] = find(X1~=0);
% finding the values of the non zero elements
vals = diag(X1(rows,cols));
%Substituting the values in X2 with 5
X2(sub2ind(size(X2),vals',cols'))=5;

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by