Question about how to make something that points to a matrix

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.

 Accepted Answer

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 Comments

That worked perfectly. Thanks. I just wanted to ask about this line. I get what it does, because it does what I asked of it, lol. but I'm not 100% sure on the process of how it does it.
y(1:end) = x(y(1:end));
I wanted to ask how does it do it? so from my understanding it looks at y 1st row all the way up to the last column of it, and it places the values of "y(1:end)" inside of x, then proceeds to place that information back into y. Is that right?
Lastly it seems like this was a easier question to answer than I thought...
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!
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 ...

Sign in to comment.

More Answers (1)

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!

Categories

Tags

Asked:

on 12 Oct 2013

Commented:

on 13 Oct 2013

Community Treasure Hunt

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

Start Hunting!