# Create a matrix with elements clockwise

4 Ansichten (letzte 30 Tage)
Alexis Pelet am 16 Jun. 2021
Kommentiert: Alexis Pelet am 16 Jun. 2021
Hello,
I would like to create a [m,n] size matrix in which the ID of the elements are created clockwise/counterclockwise.
The first element should starts in (1,1).
For example, for a matrix of size [5,8] (meaning 40 elements in total) we should have this final matrix:
This should be the result in Matlab:
##### 0 Kommentare-2 ältere Kommentare anzeigen-2 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

### Akzeptierte Antwort

Stephen23 am 16 Jun. 2021
Bearbeitet: Stephen23 am 16 Jun. 2021
More efficient:
M = spiral2(5,8)
M = 5×8
1 22 21 20 19 18 17 16 2 23 36 35 34 33 32 15 3 24 37 38 39 40 31 14 4 25 26 27 28 29 30 13 5 6 7 8 9 10 11 12
##### 1 Kommentar-1 ältere Kommentare anzeigen-1 ältere Kommentare ausblenden
Alexis Pelet am 16 Jun. 2021
It's perfect! I will not forget to mention your name in the algorithm I am creating, thank you very much!

Melden Sie sich an, um zu kommentieren.

### Weitere Antworten (1)

Joseph Cheng am 16 Jun. 2021
While probably not the most efficient way you can fill in edges like i've done here:
clc;clear all
x = zeros(5,8); %generate matrix to be filled with 0's
totN = numel(x);
indexes = 1:totN; %get values to fill in the spiral, here 1:total number for review
cnum=1; %column number to fill in
while numel(indexes)~=0 %while there is still numbers to fill in
for ind = 1:4 %rotate 4 times for 4 edges before next spiral in
zindex = find(x(:,cnum)==0); %for the leading left hand edge see which values are 0
x(zindex,cnum)=indexes(1:numel(zindex)); %fill in where there are 0's by the next 1:#zeros
indexes(1:numel(zindex))=[]; %remove values used from the list
x = rot90(x,-1); %rotate whole matrix so we're just working on a consistant edge
end
disp(x) %display matrix
cnum=cnum+1; %now we've rotated 4 times we're back to original orientation and need to spiral in (next col over)
end
1 22 21 20 19 18 17 16 2 0 0 0 0 0 0 15 3 0 0 0 0 0 0 14 4 0 0 0 0 0 0 13 5 6 7 8 9 10 11 12 1 22 21 20 19 18 17 16 2 23 36 35 34 33 32 15 3 24 0 0 0 0 31 14 4 25 26 27 28 29 30 13 5 6 7 8 9 10 11 12 1 22 21 20 19 18 17 16 2 23 36 35 34 33 32 15 3 24 37 38 39 40 31 14 4 25 26 27 28 29 30 13 5 6 7 8 9 10 11 12
##### 1 Kommentar-1 ältere Kommentare anzeigen-1 ältere Kommentare ausblenden
Alexis Pelet am 16 Jun. 2021
Even if you say it's not the most efficient way to do it, your code does the job! Thank you!!

Melden Sie sich an, um zu kommentieren.

### Kategorien

Mehr zu Logical finden Sie in Help Center und File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by