[Questions] Logical Indexing Problem

조회 수: 1 (최근 30일)
Huy Truong
Huy Truong 2015년 7월 31일
댓글: Huy Truong 2015년 7월 31일
“Write a function called trim10 that takes two vectors of the same length as input arguments (it does not have to check the format of the input) and returns two row vectors of the same length as the input vectors. If it is called like this, [v_trimmed,trimmings] = trim10(v1,v2), then v_trimmed is identical to v1 except that every element v1(ii) that is greater than v2(ii)+10 must be trimmed, which means that it must be replaced by v2(ii)+10. Each element of trimmings is equal to the amount by which each element has been trimmed. The function must use logical indexing instead of explicit looping. Here is an example of the function being used:
>>
v1
v1 =
36 26 4 17 -100 90
>> v2
v2 =
34 15 -20 0 6 80
>> [v_trimmed,trimming] = trim10(v1,v2)
v_trimmed =
36 25 -10 10 -100 90
trimmings =
0 1 14 7 0 0
Here's my code
function [v_trimmed,trimmings] = trim10(v1,v2)
% Return v_trimmed
v_trimmed = v1;
v_trimmed(v_trimmed>(v2+10)) = v2(v_trimmed>(v2+10))+10;
% Return trimmings
trimmings = zeros(1,length(v1));
for ii = 1:length(trimmings)
if v_trimmed(ii) == v1(ii)
trimmings(ii) = 0;
else
trimmings(ii) = v1(ii)-(v2(ii)+10);
end
end
end
I can't use logical indexing to find trimmings because it would return a 1x3 vector, without the 0s like the problem wants. Does any one have any suggestion on how to use logical indexing to find trimmings, or we can't use logical indexing in this case?
Thanks!

채택된 답변

Stephen23
Stephen23 2015년 7월 31일
편집: Stephen23 2015년 7월 31일
The task states clearly that the "function must use logical indexing instead of explicit looping", and using logical indexing actually makes the code much simpler than using loops anyway:
function [v_trimmed,trimming] = trim10(v1,v2)
v_trimmed = v1;
idx = v1>(v2+10);
v_trimmed(idx) = v2(idx)+10;
trimming = v1 - v_trimmed;
end
And tested using those vectors:
>> v1 = [36,26,4,17,-100,90]
v1 =
36 26 4 17 -100 90
>> v2 = [34,15,-20,0,6,80]
v2 =
34 15 -20 0 6 80
>> [v_trimmed,trimming] = trim10(v1,v2)
v_trimmed =
36 25 -10 10 -100 90
trimming =
0 1 14 7 0 0

추가 답변 (1개)

Adam
Adam 2015년 7월 31일
trimmings = max( 0, v1 - ( v2 + 10 ) )
seems to do the job.
  댓글 수: 1
Huy Truong
Huy Truong 2015년 7월 31일
I think if this problem were just to ask for finding trimmings, then your answer would be brilliant. It really shows me how a little analyzing before writing codes can make huge difference.

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

카테고리

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