How to only perform the upper triangular part of matrix operations?

조회 수: 6 (최근 30일)
Xh Du
Xh Du 2017년 4월 26일
댓글: Xh Du 2017년 4월 27일

Hi all,

I'm trying to solve this problem, where I have to use a nested loop like this:

clear; clc;
demo = zeros(4, 4);
indj = 1;
for l = 1:2
      for j = 1:2
          indi = 1;
          for k = 1:2
              for i = 1:2
                  disp([indi, indj])
                  demo(indi, indj) = 1;
                  indi = indi + 1;
              end
          end
          indj = indj + 1;
      end
  end

In this code, i, j, k, l each has 2 operations, thus total number of operations is 2^4 = 16. A 4 by 4 matrix 'demo' is filled by these 16 operations (each operation is represented by 'demo(indi, indj) = 1;'), while indi and indj are used to indicate the coordinate of these operations. 'demo' is a 4 by 4 matrix made of 1s.

>> demo
demo =
     1     1     1     1
     1     1     1     1
     1     1     1     1
     1     1     1     1

Now in my problem, because 'demo' is symmetric along the main diagonal, I'm trying to only compute the upper triangular part of 'demo' to save cost, i.e. I want 'demo' to be like:

>> demo
demo =
     1     1     1     1
     0     1     1     1
     0     0     1     1
     0     0     0     1

while the form of using i, j, k, l cannot be changed. I tried the following (only change to k = l:2 and i = j:2):

clear; clc;
  demo = zeros(4, 4);
  indj = 1;
  for l = 1:2
        for j = 1:2
            indi = 1;
            for k = l:2
                for i = j:2
                    disp([indi, indj])
                    demo(indi, indj) = 1;
                    indi = indi + 1;
                end
            end
            indj = indj + 1;
        end
    end

It doesn't work. Any ideas?

채택된 답변

James Tursa
James Tursa 2017년 4월 26일
If you can't change the looping, then maybe just insert an if-test:
if( indi <= indj )
demo(indi, indj) = 1;
end
  댓글 수: 1
Xh Du
Xh Du 2017년 4월 27일
Thanks! This works! Notice that this needs to be inserted in the first piece of code in my original question.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by