MATLAB: What is wrong with the code? Cycle while help

elseififmatrixwhile

Given a matrix called 'Heights' we should answer with a matrix called 'Path' that goes from space Heights(1,1) to space Height(m,n).
Matrix 'Heights'
10 | 12 | 15
---------------
11 | 11 | 12
---------------
13 | 14 | 15
So we are in Heights(1,1) and we can only move only – East – Southeast – South – (if the spaces have the same values we preferred first Southeast then East then South)
Matrix 'Path'
1 1 10
2 2 11
2 3 12
3 3 15
The code:
function Path = get_path(Heights)
m = 1;
n = 1;
M = [1,1,Heights(1,1)];
% Southwest = Heights(m+1,n+1)
% East = Heights(m,n+1)
% South = Heights(m+1,n)
while m <= size(Heights,1) && n <= size(Heights,2)
if m < size(Heights,1) && n < size(Heights,2)
if Heights(m+1,n+1) <= Heights(m,n+1) && Heights(m+1,n+1) <= Heights(m+1,n)
M = [M; m+1,n+1,Heights(m+1,n+1)];
elseif Heights(m+1,n+1) <= Heights(m,n+1) && Heights(m+1,n+1) > Heights(m+1,n)
M = [M; m+1,n,Heights(m+1,n)];
elseif Heights(m+1,n+1) > Heights(m,n+1) && Heights(m,n+1) <= Heights(m+1,n)
M = [M; m,n+1,Heights(m,n+1)];
elseif Heights(m+1,n+1) > Heights(m,n+1) && Heights(m,n+1) > Heights(m+1,n)
M = [M; m+1,n,Heights(m+1,n)];
end
elseif m == size(Heights,1) && n < size(Heights,2)
M = [M; m,n+1,Altitudes(m,n+1)];
elseif m < size(Heights,1) && n == size(Heights,2)
M = [M; m+1,n,Heights(m+1,n)];
elseif m == size(Heights,1) && n == size(Heights,2)
M = [M; m,n,Heights(m,n)];
end
end
Caminho = M
end
The problem is when I go to the command line and call the function is just stays blank…

Best Answer

  • You need to break out of the loop when you hit the bottom corner. Also, you need to add in code that updates m and/or n as you build the path. E.g.,
    elseif m < size(Heights,1) && n == size(Heights,2)
    M = [M; m+1,n,Heights(m+1,n)];
    m = m + 1; % <-- add code like this to other branches also
    % elseif m == size(Heights,1) && n == size(Heights,2) <-- don't need this
    % M = [M; m,n,Heights(m,n)];
    end
    if m == size(Heights,1) && n == size(Heights,2)
    break;
    end
    Your current code is an infinite loop. Stepping through the code with the debugger and examining m, n, and M as you go would have shown you this.
    What is "Altitudes"? Is that a typo?