What is wrong with my code? Cycle while help

조회 수: 5 (최근 30일)
Jaquim Cigano
Jaquim Cigano 2017년 4월 27일
댓글: Jaquim Cigano 2017년 4월 27일
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...

채택된 답변

James Tursa
James Tursa 2017년 4월 27일
편집: James Tursa 2017년 4월 27일
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?
  댓글 수: 1
Jaquim Cigano
Jaquim Cigano 2017년 4월 27일
Thank you so much! I was trying to solve this since yesterday!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 MATLAB Coder에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by