how to create diagonal movement in a matlab matrix

Thread Starter

dtrent258

Joined Jul 12, 2014
5
I have another quick question about matlab. If this is my matrix:

a=
3 3 3 3 3 3 3 3 3 3
3 3 3 3 3 3 3 3 4 3
3 3 3 3 3 3 3 3 3 3
3 3 3 3 3 3 3 3 3 3
3 3 3 3 3 3 3 3 3 3
3 3 3 3 3 3 3 3 3 3
3 3 3 3 3 3 3 3 3 3
3 3 3 3 3 3 3 3 3 3
3 1 3 3 3 3 3 3 3 3
3 3 3 3 3 3 3 3 3 3

I need to start at the 1 in the lower left hand corner, and go diagonally element by element to the 4 in the top right and change that value to a 1, the values of the other cells doesn't matter.
I started off by

p=size(a);
n=p(1);
m=p(2);
for i=1:1:n; %rows
for j=1:1:m; %columns

I'm stuck in here

end
end
a


this is where I'm stuck, I usually end up in an infinite loop somehow. I tried to use "find(a(i,j)=1)" to look for the value 1 then set that equal to a(i,j) and then do something like a(i+1,j+1) to go diagonal but it doesn't seem to work. any suggestions:
 

shteii01

Joined Feb 19, 2010
4,644
a(i+1, j+1)... take a piece of paper and pencil, your i=1, your j=1, a(i+1, j+1)=a(2,2). Do it again, i=2, j=2, a(i+1, j+1)=a(3,3). So. Instead of moving from the bottom left corner to upper right corner you are doing... what are you doing?
 

Thread Starter

dtrent258

Joined Jul 12, 2014
5
The start and end point doesn't have to be those two, it could be any two that form a diagonal line in the matrix. In my other question I needed to go through a matrix element by element starting with the top right cell and either going vertical or horizontal but always completing one row or column, moving to the next one and head back the opposite direction. the diagonals come into play when I hit an obstruction and need to avoid it. So the starting point of the diagonal could be anywhere within the matrix and go in any direction. I see what you're saying about my example above though. If I were to start at the bottom of the matrix I probably should have done this instead

i=n-1:-1;1;
j=2:1:m-1;
for my starting row and column that way a(i-1,j+1) would go up and right.... seems right when I wrote it out. I'll try it and see, but wouldn't that only work if I knew before hand where to start?
 

shteii01

Joined Feb 19, 2010
4,644
i=n-1:-1;1;
j=2:1:m-1;
for my starting row and column that way a(i-1,j+1) would go up and right.... seems right when I wrote it out. I'll try it and see, but wouldn't that only work if I knew before hand where to start?
You have to make a choice: either you know where you start or you don't.
Which case is it?

If you know where you start, then you just write the code detailing how you get from start to finish.

If yo don't know you starting point ahead of time... then things get very complicated very fast.
 
Top