Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I want to turn my code into a recursive one and i\'m having trouble. This code g

ID: 3596423 • Letter: I

Question

I want to turn my code into a recursive one and i'm having trouble. This code generates a matrix that changes the values depending on a certain condition. I created this code to replace every 0 in blank with its distance to the nearest 1 (starting at 2), traveling along cardinal directions (up, down, left and right) without passing through a -1 value. That is, all 0s that are directly next to a 1 should be changed to a 2 and all 0s next to any new 2s should be changed to 3s, and so on. Spaces with -1 values should be treated as “walls” and should stay -1. If there is no route from a 0 to a 1 without passing through a -1, it should remain a 0. The ultimate result should be that every 0 that is connected to a 1 is replaced with its distance to the nearest 1.

function [ filled ] = travelDistance( blank )

filled = blank;

  for i = 1:numel(filled)

  if filled(i) == 0 && (filled(i-1) == 1 || filled(i+1) == 1 || ...

filled(i+size(filled,1)) == 1 || filled(i-size(filled,1)) == 1)

filled(i) = 2;

  end

  end

  for i = 1:numel(filled)

  if filled(i) == 0 && (filled(i-1) == 2 || filled(i+1) == 2 || ...

filled(i+size(filled,1)) == 2 || filled(i-size(filled,1)) == 2)

filled(i) = 3;

  end

  end

     for i = 1:numel(filled)

  if filled(i) == 0 && (filled(i-1) == 3 || filled(i+1) == 3 || ...

filled(i+size(filled,1)) == 3 || filled(i-size(filled,1)) == 3)

filled(i) = 4;

  end

     end

     for i = 1:numel(filled)

  if filled(i) == 0 && (filled(i-1) == 4 || filled(i+1) == 4 || ...

filled(i+size(filled,1)) == 4 || filled(i-size(filled,1)) == 4)

filled(i) = 5;

  end

     end

end

Explanation / Answer

function [filled] = travelDistance(blank)
filled = blank;
for j = 1:4 //applying the for loop for recursion j=1,2,3,4
for i = 1:numel(filled)
if filled(i) == 0 && (filled(i-1) == j || filled(i+1) == j || ...
filled(i+size(filled,1)) == j || filled(i-size(filled,i)) == j) // j=1,2,3,4
filled(i) = j + 1; // for every loop filled = 2,3,4,5
end
end
end

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote