MATLAB: finding a row index in a matrix - matrix

I have a matrix and I want to find the maximum value in each column, then find the index of the row of that maximum value.

A = magic(5)
A =
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
[~,colind] = max(max(A))
colind =
3
returns colind as the column index that contains the maximum value. If you want the row:
[~,rowind] = max(A);
max(rowind)
ans =
5

You can use a fairly simple code to do this.
MaximumVal=0
for i= i:length(array)
if MaximumVal>array(i)
MaximumVal=array(i);
Indicies=i;
end
end
MaximumVal
Indicies

Another way to do this would be to use find. You can output the row and column of the maximum element immediately without invoking max twice as per your question. As such, do this:
%// Define your matrix
A = ...;
% Find row and column location of where the maximum value is
[maxrow,maxcol] = find(A == max(A(:)));
Also, take note that if you have multiple values that share the same maximum, this will output all of the rows and columns in your matrix that share this maximum, so it isn't just limited to one row and column as what max will do.

Related

How to extract vectors from a given condition matrix in Octave

I'm trying to extract a matrix with two columns. The first column is the data that I want to group into a vector, while the second column is information about the group.
A =
1 1
2 1
7 2
9 2
7 3
10 3
13 3
1 4
5 4
17 4
1 5
6 5
the result that i seek are
A1 =
1
2
A2 =
7
9
A3 =
7
10
13
A4=
1
5
17
A5 =
1
6
as an illustration, I used the eval function but it didn't give the results I wanted
Assuming that you don't actually need individually named separated variables, the following will put the values into separate cells of a cell array, each of which can be an arbitrary size and which can be then retrieved using cell index syntax. It makes used of logical indexing so that each iteration of the for loop assigns to that cell in B just the values from the first column of A that have the correct number in the second column of A.
num_cells = max (A(:,2));
B = cell (num_cells,1);
for idx = 1:max(A(:,2))
B(idx) = A((A(:,2)==idx),1);
end
B =
{
[1,1] =
1
2
[2,1] =
7
9
[3,1] =
7
10
13
[4,1] =
1
5
17
[5,1] =
1
6
}
Cell arrays are accessed a bit differently than normal numeric arrays. Array indexing (with ()) will return another cell, e.g.:
>> B(1)
ans =
{
[1,1] =
1
2
}
To get the contents of the cell so that you can work with them like any other variable, index them using {}.
>> B{1}
ans =
1
2
How it works:
Use max(A(:,2)) to find out how many array elements are going to be needed. A(:,2) uses subscript notation to indicate every value of A in column 2.
Create an empty cell array B with the right number of cells to contain the separated parts of A. This isn't strictly necessary, but with large amounts of data, things can slow down a lot if you keep adding on to the end of an array. Pre-allocating is usually better.
For each iteration of the for loop, it determines which elements in the 2nd column of A have the value matching the value of idx. This returns a logical array. For example, for the third time through the for loop, idx = 3, and:
>> A_index3 = A(:,2)==3
A_index3 =
0
0
0
0
1
1
1
0
0
0
0
0
That is a logical array of trues/falses indicating which elements equal 3. You are allowed to mix both logical and subscripts when indexing. So using this we can retrieve just those values from the first column:
A(A_index3, 1)
ans =
7
10
13
we get the same result if we do it in a single line without the A_index3 intermediate placeholder:
>> A(A(:,2)==3, 1)
ans =
7
10
13
Putting it in a for loop where 3 is replaced by the loop variable idx, and we assign the answer to the idx location in B, we get all of the values separated into different cells.

Find elements of given matrix

You are given an infinite matrix whose upper-left square starts with 1. Here are the first five rows of the infinite matrix :
1 2 9 10 25
4 3 8 11 24
5 6 7 12 23
16 15 14 13 22
17 18 19 20 21
Your task is to find out the number in presents at row x and column y after observing a certain kind of patter present in the matrix
Input Format
The first input line contains an integer t: the number of test cases
After this, there are t lines, each containing integer x and y
For each test, print the number present at xth row and yth column.
sample input
3
2 3
1 1
4 2
sample output
8
1
15
Hint: the numbers at the right and bottom border of a left upper square are consecutive (going either down and left, or right and up). First determine in which border your position is, then find out which direction applies, and finally find the correct number at the position (which easy formula gives you the first number in the border?).

Fastest way to find sum of any rectangle in matrix

I have a m x n matrix and want to be able to calculate sums of arbitrary rectangular submatrices. This will happen several times for the given matrix. What data structure should I use?
For example I want to find sum of rectangle in matrix
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Sum is 68.
What I'll do is accumulating it row by row:
1 2 3 4
6 8 10 12
15 18 21 24
28 32 36 40
And then, if I want to find sum of the matrix I just accumulate 28,32,36,40 = 136. Only four operation instead of 15.
If I want to find sum of second and third row, I just accumulate 15,18,21,24 and subtract 1, 2, 3, 4. = 6+8+10+12+15+18+21+24 = 68.
But in this case I can use another matrix, accumulating this one by columns:
1 3 6 10
5 11 18 26
9 19 30 42
13 27 42 58
and in this case I just sum 26 and 42 = 68. Only 2 operation instead of 8. For wider sub-matrix is is efficient to use second method and matrix, for higher - first one. Can I somehow split merge this to methods to one matrix?
So I just sum to corner and subtract another two?
You're nearly there with your method. The solution is to use a summed area table (aka Integral Image):
http://en.wikipedia.org/wiki/Summed_area_table
The key idea is you do one pass through your matrix and accumulate such that "the value at any point (x, y) in the summed area table is just the sum of all the pixels above and to the left of (x, y), inclusive.".
Then you can compute the sum inside any rectangle in constant time with four lookups.
Why can't you just add them using For loops?
int total = 0;
for(int i = startRow; i = endRow; i++)
{
for(int j = startColumn; j = endColumn; j++)
{
total += array[i][j];
}
}
Where your subarray ("rectangle") would go from startRow to endRow (width) and startColumn to endColumn (height).

Matlab best match of a sequence within a matrix

I want to find the best match of a sequence of integers within a NxN matrix. The problem is that I don't know how to extract the position of this best match. The following code that I have should calculate the edit distance but I would like to know where in my grid that edit distance is shortest!
function res = searchWordDistance(word,grid)
% wordsize = length(word); % extract the actual size
% [x ,y] = find(word(1) == grid);
D(1,1,1)=0;
for i=2:length(word)+1
D(i,1,1) = D(i-1,1,1)+1;
end
for j=2:length(grid)
D(1,1,j) = D(1,1,j-1)+1;
D(1,j,1) = D(1,j-1,1)+1;
end
% inspect the grid for best match
for i=2:length(word)
for j=2:length(grid)
for z=2:length(grid)
if(word(i-1)==grid(j-1,z-1))
d = 0;
else
d=1;
end
c1=D(i-1,j-1,z-1)+d;
c2=D(i-1,j,z)+1;
c3=D(i,j-1,z-1)+1;
D(i,j,z) = min([c1 c2 c3]);
end
end
end
I have used this code (in one less dimension) to compare two strings.
EDIT Using a 5x5 matrix as example
15 17 19 20 22
14 8 1 15 24
11 4 17 3 2
14 2 1 14 8
19 23 5 1 22
now If I have a sequence [4,1,1] and [15,14,12,14] they should be found using the algorithm. The first one is a perfect match(diagonal starts at (3,2)). The second one is on the first column and is the closest match for that sequence since only one number is wrong.

Cumulative summation of value in each row

I have something like the following:
a = [1 11; 2 16; 3 9; 4 13; 5 8; 6 14];
b = a;
n = length(a);
Sum = [];
for i=1:1:n,
Sum = b(i,2)+b(i+1:1:n,2)
end
b =
1 11
2 16
3 9
4 13
5 8
6 14
For the first iteration I am looking to find the first combination of values in the second column which are between 19 and 25.
Sum =
27
20
24
19
25
Since 20 is that first combination (Rows 1&3) -- I would like to remove that data at start a new matrix or signify that is the first combination (i.e. place a 1 next to in by creating a third column)
The next step would be to sum the values which are still in the matrix with row 2 value:
Sum =
29
24
30
Then 2&5 would be combined.
However, I would like to allow not only pairs to be combined but also several rows if possible.
Is there something I am overlooking that may simplify this problem?
I don't think you're going to simplify this very much. It's a variation on the knapsack problem, which is NP-hard. The best algorithm to use might depend on the size of your inputs.

Resources