Elements of a matrix that are greater than sum of their two indices problem
9 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Amit Tal
am 19 Aug. 2015
Kommentiert: Amit Tal
am 20 Aug. 2015
I am having trouble solving the following problem.
Prompt: Write a function called large_elements that takes as input an array named X that is a matrix or a vector. The function identifies those elements of X that are greater than the sum of their two indexes. For example, if the element X(2,3) is 6, then that element would be identified because 6 is greater than 2 + 3. The output of the function gives the indexes of such elements found in rowmajor order. It is a matrix with exactly two columns. The first column contains the row indexes, while the second column contains the corresponding column indexes. For example, the statement indexes = large_elements([1 4; 5 2; 6 0], will make indexes equal to [1 2; 2 1; 3 1]. If no such element exists, the function returns an empty array.
My attempt:
function L = large_elements(x)
[r,c] = size(x);
[r,c] = find(x > bsxfun(@plus, (1:r)', 1:c));
L = sortrows([r,c]);
Any help and/or advice would be much appreciated.
2 Kommentare
Akzeptierte Antwort
Weitere Antworten (2)
John D'Errico
am 20 Aug. 2015
Bearbeitet: John D'Errico
am 20 Aug. 2015
Actually, I like your code very much. (Hey, this is saying a lot from me.) It uses bsxfun to do a nice test.
Ok, there one main thing I might do slightly differently. USE COMMENTS! Comments are terribly valuable to make your code more readable. The fact is, one day, you will return to a piece of code, and wonder what some line, or some block of code does. You will be quite happy if you have inline documentation. Comments are FREE! Use them.
function L = large_elements(x)
[r,c] = size(x);
[r,c] = find(x > bsxfun(@plus, (1:r)', 1:c));
L = sortrows([r,c]);
One other thing I would do is to not reuse variables quite so readily. If r and c represent the size of the matrix, then don't reuse them so freely, making them represent something completely different in the very next line. Again, variables are cheap. Be willing to use new ones, with names that indicate what they represent. This makes your code more readable, by having variable names be essentially self documenting.
But the real question is, what does not work here?
x = magic(5)-10
x =
7 14 -9 -2 5
13 -5 -3 4 6
-6 -4 3 10 12
0 2 9 11 -7
1 8 15 -8 -1
L
L =
1 1
1 2
2 1
3 4
3 5
4 3
4 4
5 2
5 3
Those are the row and column indices of X that satisfy your goal. They even appear in row-major order, as opposed to the column major order that MATLAB returns by default from find.
Siehe auch
Kategorien
Mehr zu Matrix Indexing 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!