views:

846

answers:

1

I need to draw a triangle in an image I have loaded. The triangle should look like this:

1 0 0 0 0 0
1 1 0 0 0 0
1 1 1 0 0 0
1 1 1 1 0 0
1 1 1 1 1 0
1 1 1 1 1 1

But the main problem I have is that I do not know how I can create a matrix like that.

+8  A: 

You can create a matrix like the one in your question by using the TRIL and ONES functions:

>> A = tril(ones(6))

A =

     1     0     0     0     0     0
     1     1     0     0     0     0
     1     1     1     0     0     0
     1     1     1     1     0     0
     1     1     1     1     1     0
     1     1     1     1     1     1

EDIT: Based on your comment below, it sounds like you have a 3-D RGB image matrix B and that you want to multiply each color plane of B by the matrix A. This will have the net result of setting the upper triangular part of the image (corresponding to all the zeroes in A) to black. Assuming B is a 6-by-6-by-3 matrix (i.e. the rows and columns of B match those of A), here is one solution that uses indexing (and the function REPMAT) instead of multiplication:

>> B = randi([0 255],[6 6 3],'uint8');  % A random uint8 matrix as an example
>> B(repmat(~A,[1 1 3])) = 0;           % Set upper triangular part to 0
>> B(:,:,1)                             % Take a peek at the first plane

ans =

    8    0    0    0    0    0
  143  251    0    0    0    0
  225   40  123    0    0    0
  171  219   30   74    0    0
   48  165  150  157  149    0
   94   96   57   67   27    5

The call to REPMAT replicates a negated version of A 3 times so that it has the same dimensions as B. The result is used as a logical index into B, setting the non-zero indices to 0. By using indexing instead of multiplication, you can avoid having to worry about converting A and B to the same data type (which would be required to do the multiplication in this case since A is of type double and B is of type uint8).

gnovice
Lower triangular matrix function outclasses homerolled solutions.
Stefan Kendall
Yes, that's true. +1
Lukasz Lysik
Thank you this was good. my problem here is I want to multiply this matrix with matrix contain image ::> and the matrix contain image consist of 3 parameter (W,H,RGB) plz try it and see problem , then help me ..thank you
Hashim Al-Arab

related questions