This function is supposed to output smallestPosition = 1 , 3 when given: smallestPosition = FindSmalle​stElevatio​nChange(3,​[2,7,4,5])​, however I get returned smallestPosition = 1,0,3 instead, cant seem to get rid of the random zero

4 views (last 30 days)
function [smallestPosition] = FindSmallestElevationChange(currentPosition,FuturePositions)
%This function will calculate the difference between current position, and
%available positions, in reference to elevation, by considering an array of
%values and returning the smallest difference.
% Inputs : currentPosition - single integer
% FuturePositions - 1D Array
% Outputs : smallestPosition - 1D array with smallest elevation change
%Author: Tai Leong
%calculate difference between currentPostion value and each element of
%FuturePositions
for i = 1: length(FuturePositions)
if FuturePositions(i) >= currentPosition
change = FuturePositions(i) - currentPosition;
else
change = currentPosition - FuturePositions(i);
end
elevationChange(i) = change;
end
%set smallest difference(s) into 1D array
smallestvalue = min(elevationChange);
for j = 1 : length(elevationChange)
if (elevationChange(j) == smallestvalue)%display position that produces smallest elevation change
smallestPosition(j) = j;
end
end

Answers (1)

Jan
Jan on 17 Sep 2017
Edited: Jan on 17 Sep 2017
smallestPosition = [];
for j = 1 : length(elevationChange)
if (elevationChange(j) == smallestvalue)
% Not the j.th element: smallestPosition(j) = j;
% But append to the output:
smallestPosition = [smallestPosition, j];
end
end
You will see a small red mark in the editor and a message, which tells you that the iterative growing of a vector is not efficient. For such tiny problems this does not matter. But for productive code, this is better:
smallestPosition = zeros(size(elevationChange));
for j = 1 : length(elevationChange)
if (elevationChange(j) == smallestvalue)
smallestPosition(j) = j;
end
end
smallestPosition = smallestPosition(smallestPosition ~= 0);
Finally note that the abs() command would be much cleaner and faster than the first loop, and that the loops are not needed at all. I assume that this is a homework - this is not the only thread concerning this question. An efficient solution needs 2 lines of code only and it is hard to give any further hints without posting the complete solution.

Tags

Community Treasure Hunt

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

Start Hunting!