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

47 次查看(过去 30 天)
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 个评论
Aditya Ramesh
Aditya Ramesh 2022-3-22
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 2022-3-22
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

请先登录,再进行评论。

采纳的回答

Matt J
Matt J 2022-3-22
[~,J,I]=find(gridsupplyidx);
idx=sub2ind(size(gridsupply),I,J);
gridsupply(idx)=5;

更多回答(1 个)

Aditya Ramesh
Aditya Ramesh 2022-3-22
编辑:Aditya Ramesh 2022-3-22
% 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;

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by