Look up corresponding element in a matrix
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Jay
am 18 Okt. 2014
Kommentiert: Image Analyst
am 19 Okt. 2014
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?
0 Kommentare
Akzeptierte Antwort
Image Analyst
am 18 Okt. 2014
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
2 Kommentare
Image Analyst
am 19 Okt. 2014
Justin's "Answer" transferred here.
Thankyou Image Analyst,
I was able to get this part of my code to work based on your above example.
What is the reason I can not transpose the (1,n) xFrom, yFrom, xTo and yTo matrices to be (n,1) vectors?
Image Analyst
am 19 Okt. 2014
You should be able to transpose column vectors into row vectors and row vectors into column vectors with the ' operator:
xFrom = xFrom';
and so on. Since you said it's working, can you go ahead and mark the answer as Accepted? Thanks.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!