Generate array of sequence pairs without iteration

1 回表示 (過去 30 日間)
Sabyrzhan Tasbolatov
Sabyrzhan Tasbolatov 2023 年 1 月 29 日
コメント済み: Dyuman Joshi 2023 年 1 月 29 日
If I have M = 13; N = 8; and I need following result
[1 1; 1 2; 1 3; 1 4; 1 5; 1 6; 1 7; 1 8;...
2 1; 2 2; 2 3; 2 4; 2 5; 2 6; 2 7; 2 8; 3 1; ... 13 7; 13 8]
is there any built-in MATLAB functions to achieve this without iteration? I've tried repmat but couldn't figure out how to get the exact result.
Working solution is:
a = [];
for m = 1:13
for n = 1:8
a = [a [m n]];
end
end
Thanks
  1 件のコメント
Stephen23
Stephen23 2023 年 1 月 29 日
The standard MATLAB approach is to use NDGRID or MESHGRID:
M = 13;
N = 8;
[x,y] = meshgrid(1:M,1:N);
a = [x(:),y(:)]
a = 104×2
1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 2 1 2 2

サインインしてコメントする。

採用された回答

Dyuman Joshi
Dyuman Joshi 2023 年 1 月 29 日
編集済み: Dyuman Joshi 2023 年 1 月 29 日
A combination of repelem and repmat -
M=13;N=8;
%corresponding arrays
m=1:M;n=1:N;
out1=[repelem(m',N,1) repmat(n',M,1)]
out1 = 104×2
1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 2 1 2 2
out1(end,:)
ans = 1×2
13 8
There is a function - combvec, however, it is a part of a toolbox -
out2=rot90(combvec(n,m),-1)
out2 = 104×2
1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 2 1 2 2
out2(end,:)
ans = 1×2
13 8
  2 件のコメント
Sabyrzhan Tasbolatov
Sabyrzhan Tasbolatov 2023 年 1 月 29 日
Thanks, first out1 works for me, though it needed to be in 1D with 2D elements [1 1; 1 2; 1 3; ...]
Dyuman Joshi
Dyuman Joshi 2023 年 1 月 29 日
"in 1D with 2D elements [1 1; 1 2; 1 3; ...]"
Do you mean like this?
[1 1 1 2 1 3 .. 13 8]
If yes, then you have inserted the semi-colon incorrectly in both your statements, it should be a regular comma. The way to achieve that would be -
M=13;N=8;
out=reshape([repelem(1:M,1,N);repmat(1:N,1,M)],1,[])
out = 1×208
1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 2 1 2 2 2 3 2 4 2 5 2 6 2 7

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeGet Started with MATLAB についてさらに検索

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by