1
votes

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

1
why do you want to solve it without diag and eye commands?Max
Hint: see the result of bsxfun(@eq, 1:n, (1:n).'). Try to understand how it works and turn it into your desired outputLuis Mendo
Thanks Luis I'm searching to find how it works nowRune Knight

1 Answers

0
votes

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