repeat values within array

조회 수: 12 (최근 30일)
Kati
Kati 2021년 6월 4일
댓글: Kati 2021년 6월 26일
Hi,
I have an array, that I need to extend. In specific I need to repeat each value n times. n is the length of another vector. I can select the number of value that needs to be repeated and I can repeat it, but I can't append it to the other repeated values in my for loop. It only shows the repetition of the last value. My code is as followed:
X=[0.5;0.5;0.6;0.6];
Y=[0.6;0.7;0.6;0.7];
dx=0.05;
dy=0.05;
X_klein=[min(X):dx:max(X)]';
Y_klein=[min(Y):dy:max(Y)]';
for m=1:length(X_klein)
XX=X_klein(m);
XX1=repmat(XX,length(Y_klein),1);
XX1(m)=[XX1(m);XX1];
end

채택된 답변

Rik
Rik 2021년 6월 4일
You can edit your code using a cell array for the long way round:
X=[0.5;0.5;0.6;0.6];
Y=[0.6;0.7;0.6;0.7];
dx=0.05;
dy=0.05;
X_klein=[min(X):dx:max(X)]';
Y_klein=[min(Y):dy:max(Y)]';
XX1=cell(1,numel(X_klein));
for m=1:numel(X_klein)
XX=X_klein(m);
XX1{m}=repmat(XX,numel(Y_klein),1);
end
XX1=cell2mat(XX1);
disp(XX1)
0.5000 0.5500 0.6000 0.5000 0.5500 0.6000 0.5000 0.5500 0.6000
Or use meshgrid for the shorter way:
[XX1,YY1]=meshgrid(X_klein,Y_klein);
disp(XX1)
0.5000 0.5500 0.6000 0.5000 0.5500 0.6000 0.5000 0.5500 0.6000
  댓글 수: 4
Kati
Kati 2021년 6월 26일
I'm sorry, I still don't understand it. It's always the 3x3 matrix, but I need it in 9x1..
Kati
Kati 2021년 6월 26일
I solved it.Thank you for your help!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by