MATLAB: [Questions] Logical Indexing Problem

logical indexing

“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 1×3 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!

Best Answer

  • 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