Replace certain Values within a Matrix Based on Indices from Another matrix
23 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Ritika Srinivasan
el 22 de Mzo. de 2022
Comentada: Ritika Srinivasan
el 22 de Mzo. de 2022
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 comentarios
Aditya Ramesh
el 22 de Mzo. de 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)?
Respuesta aceptada
Matt J
el 22 de Mzo. de 2022
[~,J,I]=find(gridsupplyidx);
idx=sub2ind(size(gridsupply),I,J);
gridsupply(idx)=5;
Más respuestas (1)
Aditya Ramesh
el 22 de Mzo. de 2022
Editada: Aditya Ramesh
el 22 de Mzo. de 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;
2 comentarios
Ver también
Categorías
Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!