A function called small_elements that takes as input an array named X that is a matrix or a vector. Could you help me to understand the meaning?

조회 수: 1 (최근 30일)
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.
I'm not native english speaker so I can't understand very well. My question is..why the function returns a "3"?
Thank you for your help!

답변 (2개)

Walter Roberson
Walter Roberson 2017년 8월 28일
For a 3 x 2 input named x, the logic is like
if x(1,1) < 1*1
disp([1, 1])
end
if x(1,2) < 1*2
disp([1, 2])
end
if x(2,1) < 2*1
disp([2, 1])
end
if x(2,2) < 2*2
disp([2, 2])
end
if x(3, 1) < 3*1
disp([3, 1])
end
if x(3, 2) < 3*2
disp([3, 2])
end

RAMAKANT SHAKYA
RAMAKANT SHAKYA 2019년 2월 7일
function ind=small_elements(v)
[m,n]=size(v);
j=0;
ind=[];
for c=1:n
for r=1:m
if (r*c) > v(r,c)
j=j+1;
s=[r c];
ind=vertcat(ind,s); %adding matrix vertically
end
end
end
end
  댓글 수: 1
Stephen23
Stephen23 2019년 2월 7일
편집: Stephen23 2019년 2월 7일
Vectorized code is much simpler and most likely more efficient:
>> X = [1,1;0,4;6,5]
X =
1 1
0 4
6 5
>> S = size(X);
>> [R,C] = find(X<((1:S(1)).' .* (1:S(2))));
>> Z = [R,C]
Z =
2 1
1 2
3 2

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by