1

I'm fairly new to MATLAB and I need some help with this problem.

the problem is to write a function that creates an (n-n) square matrix of zeros with ones on the reverse diagonal I tried this code:

function s=reverse_diag(n)
    s=zeros(n);
    i=1;j=n;
    while i<=n && j>=1
        s(i,j)=1;
        i=i+1;
        j=j-1;
    end

but I want another way for solving it without using loops or diag and eye commands.

Thanks in advance

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147

1 Answers1

0

The easiest and most obvious way to achieve this without loops would be to use

s=fliplr(eye(n))

since you stated that you don't want to use eye (for whatever reason), you could also work with sub2ind-command. It would look like this:

s=zeros(n);
s(sub2ind(size(s),1:size(s,1),size(s,2):-1:1))=1
Max
  • 1,471
  • 15
  • 37
  • Thank you max ...that is exactly what I was looking for :D – Rune Knight Jul 03 '17 at 23:15
  • 1
    @RuneKnight You're welcome. If you're trying to get used to vectorization in matlab, you should also consider dealing with Luis Mendos comment, since `bsxfun` is an awesome tool for that. – Max Jul 03 '17 at 23:19
  • I'm currently researching how this command works ...but what to do you mean by vectorization ? – Rune Knight Jul 03 '17 at 23:24
  • 1
    @RuneKnight have a look at the vectorization-tag description: https://stackoverflow.com/tags/vectorization/info. Vectorization means using funtions on whole arrays instead of looping through the array. – Max Jul 03 '17 at 23:28