Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

[Homework] While + If + Matrix (program crashing)

조회 수: 5 (최근 30일)
Jaquim Cigano
Jaquim Cigano 2017년 4월 26일
마감: MATLAB Answer Bot 2021년 8월 20일

Hello. I have a homework that the objective is to select the best path we could take, having a given matrix (matrix with heights) called 'Heights'.

This is a example (green is the path we take)

We start at (1,1) and need to go to (i,j) [in this case (4,4)]. And the preferred way to go is SouthEast > East > South. If we have the same value in the southeast block and the south block, we go to the southeast block.

Also we need to check first what is the difference of heights from the block we are to the block we want to go

So in the case, we go to the SouthEast block since is the one we "move" less.

In the end it ask to us, to make a matrix with the results. With the example I gave you, when we call the function we should get:

M =  1  1  10
     2  2  11
     2  3  15
     3  3  18
     3  4  19
     4  4  21

_______________________________________________________________________________ _______________________________________________________________________________

Now the code I make:

function res = get_path(Heights)
      i = 1;
      j = 1;	
      M = [1,1,Heights(1,1)];
      while i <= size(Heights,1) && j <= size(Heights,2)
        if abs(Heights(i,j) - Heights(i+1,j+1)) <= abs(Heights(i,j) - Heights(i,j+1)) && abs(Heights(i,j) - Heights(i+1,j+1)) <= abs(Heights(i,j) - Heights(i+1,j))
          x = i+1;
          y = j+1;
          h = Heights(i+1,j+1);
        elseif abs(Heights(i,j) - Heights(i+1,j+1)) <= abs(Heights(i,j) - Heights(i,j+1)) && abs(Heights(i,j) - Heights(i+1,j+1)) > abs(Heights(i,j) - Heights(i+1,j))
          x = i+1;
          y = j;
          h = Heights(i+1,j);
        elseif abs(Heights(i,j) - Heights(i+1,j+1)) > abs(Heights(i,j) - Heights(i,j+1)) && abs(Heights(i,j) - Heights(i,j+1)) <= abs(Heights(i,j) - Heights(i+1,j))
          x = i;
          y = j+1;
          h = Heights(i,j+1);
        else abs(Heights(i,j) - Heights(i+1,j+1)) > abs(Heights(i,j) - Heights(i,j+1)) && abs(Heights(i,j) - Heights(i,j+1)) > abs(Heights(i,j) - Heights(i+1,j))
          x = i+1;
          y = j;
          h = Heights(i+1,j);
        end
        M = [M; x,y,h]; 
      end
      res = M
end

I think the code is right, but when I go to the command line, and write: get_path(Heights) it change line and then I cant write anything.

답변 (0개)

이 질문은 마감되었습니다.

Community Treasure Hunt

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

Start Hunting!

Translated by