Replace Only Certain Values within a Matrix Based on Indices from Another

조회 수: 31 (최근 30일)
Hi all!
I have a 200 X 500 matrix. Within that matrix, only a handful of elements have actual numerical values. I have identified the index position of these numerical values (ind), and I will use the indices to look at another 200 x 500 matrix and find the values at the specified index position. (For example, if the first matrix had a numerical value at the 150th index position, I will look at the 150th index position of the second matrix and keep that value.) However, I want to keep ONLY the values from the second matrix at the index positions I identified in the first matrix, while all of the other values in the matrix are turned to zeros or NaNs. (Whereas the first matrix only has a handful of elements with actual numerical values, the second matrix has a numerical value for all elements.) So, I'm trying to keep the same matrix size (200 x 500), but I want to keep only the values at the index position I identified in the first matrix. Any idea how to do this?
Here's what I have so far...
x ***first matrix (only a few elements have numerical values)
y ***second matrix (all elements have numerical values)
ind = find(x~=0)
y(ind) ***this only gives me the values at the index position but I would like to keep values within matrix structure

채택된 답변

Michelle De Luna
Michelle De Luna 2021년 2월 13일
Got it! Thanks for the help! :)
x
y
ind = find(x~=0)
index=setdiff(1:numel(y),ind);
y(index)=0
y

추가 답변 (1개)

Image Analyst
Image Analyst 2021년 2월 13일
See if this gives you what you want:
y = y .* ind;
If not, then attach your x and y in a .mat file and tell us what you expect as an output.
  댓글 수: 2
Michelle De Luna
Michelle De Luna 2021년 2월 13일
Image Analyst, thank you for responding so quickly! I tried running your code, but the error message states the matrix dimensions must agree (i.e. the "ind" variable is of size 200x1 while the "y" variable is a matrix of size 200x500). What I hope my output will look like is a 200x500 matrix mostly filled with zeros, with the exception of numerical values at the "ind" positions. Let me try to upload a .mat file (it's my first time uploading, so let me see how it goes).
Image Analyst
Image Analyst 2021년 2월 14일
You should have used
ind = x ~= 0; % Don't use find()

댓글을 달려면 로그인하십시오.

카테고리

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