Info

This question is closed. Reopen it to edit or answer.

Why does the auto-evaluation code give me an error for the last argument ?

2 views (last 30 days)
I'm following a tutorial on coursera and trying to solve this problem:
Write a function called small_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 smaller than the product of their two indexes. For example, if the element X(2,3) is 5, then that element would be identified because 5 is smaller than 2 * 3. The output of the function gives the indexes of such elements found in column-major 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 = small_elements([1 1; 0 4; 6 5], will make indexes equal to [2 1; 1 2; 3 2]. If no such element exists, the function returns an empty array.
This is my work so far :
function D = small_elements(X)
[M,N] = size(X);
D = [];
for r = 1:M
for c = 1:N
if X(r,c) < (r*c)
D = [D ; r c];
end
end
end
end
and this is what I get:
Problem 3 (small_elements):
Feedback: Your function performed correctly for argument(s) [1 2;3 4]
Feedback: Your function performed correctly for argument(s) [1 2 3 4;5 6 7 8]
Feedback: Your function performed correctly for argument(s) [1 5;2 6;3 7;4 8]
Feedback: Your function performed correctly for argument(s) [1 2 3 4 5 6 7 8 9 10]
Feedback: Your function performed correctly for argument(s) [0;1;2;3;4;5;6;7;8;9;10]
Feedback: Your function performed correctly for argument(s) [0 1 2 3 4 5 6 7 8 9 10]
Feedback: Your function performed correctly for argument(s) 1
Feedback: Your function performed correctly for argument(s) 0
Feedback: Your function made an error for argument(s) [6 5;-3 9;-1 -8;2 -1;7 -4;-2 2;6 7]
Your solution is _not_ correct.

Answers (1)

Steven Lord
Steven Lord on 16 Jan 2019
From the assignment: The output of the function gives the indexes of such elements found in column-major order.
Does your function return the indices in column-major order?
ind = sub2ind(size(X), D(:, 1), D(:, 2))
If your function does, the elements in ind should be sorted in increasing order. Let's look at how you're "walking" through your array. The first element your nested for loops visit is the one where the 1 is in walk, the second where the 2 is, etc.
[M,N] = size(X);
walk = zeros(size(X));
q = 1;
for r = 1:M
for c = 1:N
walk(r, c) = q;
q = q+1;
end
end
walk
You're walking the matrix in row-major order. How would you modify the code to walk in column-major order?

Products


Release

R2016b

Community Treasure Hunt

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

Start Hunting!