How do I fix my code to produce ones along the reverse diagonal?

32 vues (au cours des 30 derniers jours)
Alexandra Huff
Alexandra Huff le 7 Août 2016
Commenté : Bruno Luong le 12 Juin 2020
Hi, I am having a problem with my code.
function I = reverse_diag(n)
I = zeros(n);
I(1: n+1 : n^2)=1;
I want my code to produce the ones on the reverse diagonal (top right to bottom left). I tried using fliplr because I believe, as of now, this is just a diagonal of ones from top left to bottom right. However, that is not working. Any suggestions?
  2 commentaires
Image Analyst
Image Analyst le 7 Août 2016
Modifié(e) : Image Analyst le 7 Août 2016
Alexandra, you might like to read this link on formatting and this link so you can post better questions. You put code as text, and text as code format. I'll fix it this time for you. Also, you might give more descriptive subject lines - all your posts are like "how do I fix my code?" even though they're on different topic.
Don't forget to look at my answer below.
Nava  Subedi
Nava Subedi le 15 Nov 2016
Modifié(e) : Nava Subedi le 15 Nov 2016
function s = reverse_diag(n)
I = zeros(n);
I(1: n+1 : n^2)=1;
s = flip(I, 2) % this line will reverse the elements in each row.

Connectez-vous pour commenter.

Réponse acceptée

Star Strider
Star Strider le 7 Août 2016
Modifié(e) : Star Strider le 7 Août 2016
Assuming you can’t use the eye function, this works:
n = 5;
I = zeros(n);
for k1 = 1:n
I(k1, end-k1+1) = 1;
end
I =
0 0 0 0 1
0 0 0 1 0
0 0 1 0 0
0 1 0 0 0
1 0 0 0 0
EDIT — Added output matrix.

Plus de réponses (3)

James Tursa
James Tursa le 15 Nov 2016
Yet another way using linear indexing:
I = zeros(n);
I(n:n-1:end-1) = 1;
  6 commentaires
Harshith Dhananjaya
Harshith Dhananjaya le 9 Juin 2020
I tried this piece of code:
I = zeros(n);
I(n:n-1:end-1) = 1;
The result when n=1 provides answer [0] instead of [1]. All the other size matrices works fine.
Bruno Luong
Bruno Luong le 12 Juin 2020
Correct, this is a bug for n==1. One can make it works for any n>=1 (but still not for n==0) with
I([1,n:n-1:1-1]) = 1;

Connectez-vous pour commenter.


Image Analyst
Image Analyst le 7 Août 2016
Try this:
n = 5; % Whatever...
I = fliplr(eye(n))
I =
0 0 0 0 1
0 0 0 1 0
0 0 1 0 0
0 1 0 0 0
1 0 0 0 0

mouellou
mouellou le 21 Déc 2018
Hi,
I'm a little late but I'm taking this class on coursera and here's my answer:
function I = reverse_diag(n)
I = zeros(n);
I(end-(n-1):-(n-1) : n)=1;
end
Hope it'll help someone

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by