[Questions] Logical Indexing Problem

2 views (last 30 days)
“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!

Accepted Answer

Stephen23
Stephen23 on 31 Jul 2015
Edited: Stephen23 on 31 Jul 2015
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

More Answers (1)

Adam
Adam on 31 Jul 2015
trimmings = max( 0, v1 - ( v2 + 10 ) )
seems to do the job.
  1 Comment
Huy Truong
Huy Truong on 31 Jul 2015
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.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!