how to put the same value in a number of lines in the first column of a matrix and different values in the second column (values coming from vectors)

1 回表示 (過去 30 日間)
Hello everyone,
My problem is that i have to report values from 2 vectors (of positions) in a matrix of (nx2), and for each value of the first vector (first columns) i should have m values in the second column and so on.
EXAMPLE :
vect_1=1:1:2;
vect_2=1:1:4;
%i want have this in my matrix
1 1
1 2
1 3
1 4
2 1
2 2
2 3
2 4
I'm a debutant in Matlab, so i tried some loops but it never does what i want.
Thank you, for helping.

採用された回答

Jonas
Jonas 2021 年 6 月 26 日
for the first column have a look into repelem(), for the second column have a look into repmat()
if you need more detailed help, just tell us
  3 件のコメント
Jonas
Jonas 2021 年 6 月 27 日
does this exanple help you? nrOfReps is the number of tepetitions of vector 2 and repelem repeats the elemts of vector 1 according to vector length of vector 2 compared to length of vector 1 and number of tepetitions of vector 2
nrOfReps=2;
vect1=(1:2)';
vect2=(1:4)';
mat(:,1)=repelem(vect1,length(vect2)/length(vect1)*nrOfReps);
mat(:,2)=repmat(vect2,[nrOfReps 1])
Myssipsa Mehraz
Myssipsa Mehraz 2021 年 6 月 29 日
It does exactly what i want. Now i have to expand it for several vectors.
Thank you.

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

その他の回答 (1 件)

Stephen23
Stephen23 2021 年 6 月 29 日
編集済み: Stephen23 2025 年 7 月 27 日
The simple MATLAB approach is to leverage NDGRID:
v1 = 1:1:2;
v2 = 1:1:4;
[m2,m1] = ndgrid(v2,v1);
m = [m1(:),m2(:)]
m = 8×2
1 1 1 2 1 3 1 4 2 1 2 2 2 3 2 4
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
Can be extended to any number of vectors (although you will run out of memory very quickly):
C = {v1,v2}; % any number of vectors
N = numel(C);
[C{end:-1:1}] = ndgrid(C{end:-1:1});
m = reshape(cat(N+1,C{:}),[],N)
m = 8×2
1 1 1 2 1 3 1 4 2 1 2 2 2 3 2 4
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by