MATLAB: Look up corresponding element in a matrix

element search

I have a matrix with multiple stations IDs and associated coordinate values along the stations rows (Matrix 1).
I have another matrix (Matrix 2) that in the first row has the "from" stations and in the second row has the "to" stations.
Using the station numbers specified in Matrix 2 (for both the from and to stations ), I need to look up the two station numbers from Matrix 1 and call the X-coordinates and Y-coordinates.
Is there a search function that will search for a number in a column and return the elements location of that matrix?

Best Answer

Try this:
clc; % Clear the command window.
clear all;
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
matrix2 = randi(9, 2, 10);
matrix1 = randi(9, 20, 3);
numColumns = size(matrix2, 2);
xFrom = zeros(1, numColumns);
yFrom = zeros(1, numColumns);
xTo = zeros(1, numColumns);
yTo = zeros(1, numColumns);
for station = 1 : numColumns % for every column in matrix 2...
fprintf('Examining column %d...\n', station);
% Get the station number in this column
fromStation = matrix2(1, station)
toStation = matrix2(2, station)
% Find rows in matrix 1 where the "fromStation" is located.
fromRow = find(matrix1(:, 1) == fromStation);
% Find rows in matrix 1 where the "toStation" is located.
toRow = find(matrix1(:, 1) == toStation);
% Now assume that the From station and To station are just one value each
% Get the x and y coordinates from the "from" station.
if ~isempty(fromRow)
xFrom(station) = matrix1(fromRow(1), 2);
yFrom(station) = matrix1(fromRow(1), 3);
end
% Get the x and y coordinates from the "to" station.
if ~isempty(toRow)
xTo(station) = matrix1(toRow(1), 2);
yTo(station) = matrix1(toRow(1), 3);
end
end