필터 지우기
필터 지우기

Loop multidimensional array doesn't work

조회 수: 1 (최근 30일)
Armando MAROZZI
Armando MAROZZI 2021년 7월 4일
댓글: Armando MAROZZI 2021년 7월 4일
Let's say I have some data TxN. The first column (N_1) of the data changes every time, while the rest stays fixed. Therefore, I want to create a multidimensional array TxNxM, where M takes care of the different N_1s.
Let me take an example to make it clearer:
% original data where x changes every time while z is always the same
x = randn(100,10);
z = ones(100, 5);
% this is just one of the 10 datasets
y = [x(:,1),z];
% store results
Y = nan(size(y,1), size(y,2),size(x,2));
% Create 10 datasets where the first column changes every time (x(:,i))
% while the rest stays fixed
for i = size(x,2)
Y(:,:,i) = [x(:,i), z];
end
The issue with this is that I only get data for the last column of x while all the rest is NaN.
What am I doing wrong?
Can anyone help me?

채택된 답변

Matt J
Matt J 2021년 7월 4일
편집: Matt J 2021년 7월 4일
You could fix it by changing the opening of your for-loop to,
for i = 1:size(x,2)
but below is a more efficient loop-free method.
Y = nan(size(y,1), size(y,2),size(x,2));
Y(:,1,:)=x;
Y(:,2:end,:)=repmat(z,1,1,size(x,2));
  댓글 수: 3
Matt J
Matt J 2021년 7월 4일
I would like to note, though, that it seems a bit wasteful to put so much duplicate data in Y. I don't see why working with x and z as separate arrays wouldn't be preferred.
Armando MAROZZI
Armando MAROZZI 2021년 7월 4일
I see your points. However, I need to apply a function to different datasets (of the same type you saw above) and that's the quickest solution I came up with

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

추가 답변 (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