[Questions] Logical Indexing Problem

1 次查看(过去 30 天)
“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