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 Center および File ExchangeMATLAB Coder についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by