0
votes
function[output]=tridiag(d,l,r)
A=zeros(3);
for i=1:5 
    A(i,i)=d(i);
    for j=2:5
        A(j,(i-1))=l(j);
        for k=1:4
            A(k,(i+5))=r(k);
        end
    end
end
A
end

on this part where it says,

for j=2:5
    A(j,(i-1))=l(j);

I want the variable "i" to execute from 1 ~ 4. and not 5. That's why I put i-1 there, but obviously it won't work.

How can I make the nested j-loop to repeat i=1:4, instead of i=1:5? Same question goes for k-loop too.

+update: So I want the outside i-loop to perform from 1:5, but for the inner j-loop, i want i=1:4.

3
Change the line for i=1:5 to for i=1:4. Similarly for the loop over j - Drake
@Drake no, because that will make the initial i-loop to repeat from 1 to 4. I want the outside loop to repeat from 1:5. Only the in the inside j-loop, i want i to be 1:4 - Eric Kim
Well, you should have stated that clearly from the beginning. Wrap the inner loop in an if statement: if (i < 5) - Drake
Actually, could you show an example input and output? I can guess you want to create a tri-diagonal matrix but can't decipher what is in d,l,r - Yvon

3 Answers

0
votes

To your original question: Use loop control in the inner loop.

for i=1:5 
    A(i,i)=d(i);
    for j=2:5
        if i==5
            continue
        end
        A(j,(i-1))=l(j);
        for k=1:4
            A(k,(i+5))=r(k);
        end
    end
end

I guess you want to create a tridiagonal matrix using d as the major diagonal line, l as the left/lower diagonal, and r as the right/upper diagonal. Your code does not seem to work due to wrong indexing.

d = 1:5;
l = 10:10:50;
r = 100:100:500;

N = length(d);
A=zeros(N);
for ii=1:N
    A(ii,ii)= d (ii);
    if ii~=1
        A(ii,(ii-1)) = l(ii);
    end
    if ii~=N
        A(ii,(ii+1)) = r(ii);
    end
end
A


A =

     1   100     0     0     0
    20     2   200     0     0
     0    30     3   300     0
     0     0    40     4   400
     0     0     0    50     5
0
votes
A(j,(i-1))

i starts from 1. So in the first iteration, this give you:

A(j,(0))

Since the index of an array in MATLAB starts from 1, this is definitely wrong. So change your code to something like this will work:

for j=1:4
    A(j,(i))=l(j);
0
votes
function[output]=tridiag(d,l,r)
A=zeros(3);
for i=1:5 
      A(i,i)=d(i);
      j=2;
      while(j<6 & i~=5)
             A(j,i)=l(j);
             j=j+1;
                for k=1:4
                A(k,(i+5))=r(k);
             end
       end
end
A
end

The below three lines make sure that 'j' runs from '2' to '5' for every value of 'i' except i=5 .

j=2;
while(j<6 & i~=5)
j=j+1;