Finding the highest value in a matrix using dynamic programming starting from top left to bottom right.
Afficher commentaires plus anciens
I am trying to move top left of the matrix to bottom right, with right and down movements counting as -1 and not taking the data in the matrix. Only diagonal movements can be added. From my code, I am getting 24 instead 17 and I am not sure why. path should be down, -1, 19,18, then 17
data=[0 5 1 100; 1 1 5 1; 1 20 1 5]
dp=zeros(size(data));
for i = 2:size(data, 1)
dp(i,1)=-1+ dp(i,1);
end
for j = 2:size(data, 2)
dp(1,j)=-1+ dp(1,j);
end
options=[];
for i = 2:size(data, 1)
for j = 2:size(data, 2)
options=[];
if i==1 && j==1
best=data(1,1)
break
end
if j>1
moveRight = dp(i, j-1)-1;
options(end+1)=moveRight;
dp(i, j)=moveRight;
end
if i>1
moveDown = dp(i-1, j)-1;
options(end+1)=moveDown;
dp(i, j)=moveDown;
end
if i>1 && j>1
moveDiagonal = dp(i-1, j-1);+ data(i, j);
options(end+1)=moveDiagonal;
dp(i, j) = data(i, j) + max(options);
end
end
end
highestValue = dp(end, end)
3 commentaires
Matt J
le 3 Fév 2024
So, the problem is resolved?
Anthony Chan
le 3 Fév 2024
dpb
le 3 Fév 2024
data=[0 5 1 100; 1 1 5 1; 1 20 1 5];
dp=zeros(size(data));
dp(2:end,1)=-1;
dp(1,2:end)=-1;
dp
I don't understand the problem description enough to know what the problem trying to be solved actually is, but "the MATLAB way" in the initialization phase is to use array indexing vector operations as show above.
If the problem is one of decision making on a stepwise basis, then a loop construct is probably required, but learning the basics of array indexing operations early on is a key to productive use of MATLAB.
Réponse acceptée
Plus de réponses (0)
Catégories
En savoir plus sur Univariate Discrete Distributions dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!