Clear Filters
Clear Filters

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

47 views (last 30 days)
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 Comments
Aditya Ramesh
Aditya Ramesh on 22 Mar 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 on 22 Mar 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

Sign in to comment.

Accepted Answer

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

More Answers (1)

Aditya Ramesh
Aditya Ramesh on 22 Mar 2022
Edited: Aditya Ramesh on 22 Mar 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;

Products

Community Treasure Hunt

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

Start Hunting!