Question about how to make something that points to a matrix

조회 수: 1 (최근 30일)
Gilmar
Gilmar 2013년 10월 12일
댓글: Jos (10584) 2013년 10월 13일
I'm pretty new to matlab, so sorry if my question seems a bit dumb to ask or vague.
Example:
x=[11, 3, 5, 7, 1, 8, 9];
y=[1, 2];
I have a program that gives me a matrix x and I made another program that outputs matrix y. What matrix y is doing is searching for a specific value in some other matrix and its telling me what columns that specific value is in, and it gets saved into matrix y. In this example the specific value I'm looking for is in column 1, and 2.
So what I now want to do with these 2 matrices is make matrix y point to matrix x, and return the values in x to y.
Meaning matrix y tells me that the specific value I want is in columns 1 and 2, now I want to tell matrix y to look at matrix x, and see that for the 1st column we have 11, and for column 2 we have 3, now replace the y=[1, 2] with y=[11, 3].
So for another example we could have had y=[1, 4], and the program would know that it correlates with the values 11, and 7, and replace matrix y with a new matrix y=[11, 7].
Basically I want the program to know that each value it has in matrix y relates to a specific column in the 1x7 matrix x.
I tried doing some case structure, but it failed to run properly.

채택된 답변

sixwwwwww
sixwwwwww 2013년 10월 12일
편집: sixwwwwww 2013년 10월 12일
Dear Gilmar, here is the code:
x = [11, 3, 5, 7, 1, 8, 9];
y = [1, 2];
if max(y) > length(x)
error('Maximum column index pointer in y is greater than length of vector x')
else
y(1:end) = x(y(1:end));
end
disp(y)
Good luck!
  댓글 수: 3
sixwwwwww
sixwwwwww 2013년 10월 12일
Yes you are right. It works exactly as you described. Yes it was an easy question. You can post any questions relevant to MATLAB which you feel are answerable here. Good luck!
Jos (10584)
Jos (10584) 2013년 10월 13일
You should remove the obfuscating "1:end" bit
y = x(y)
or in case you want to safe the original values
new_y = x(y)
would do ...

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

추가 답변 (1개)

Jos (10584)
Jos (10584) 2013년 10월 12일
Try this
x = [11 13 15 21]
x(2)
x([1 3])
x([4 2])
y = [3 2 4]
x(y) % voila!
x(20) % oops!

카테고리

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