필터 지우기
필터 지우기

Inserting columns of one matrix between the columns of another matrix

조회 수: 4 (최근 30일)
Hello,
I have two matrices as follows :
Sorted_grid of size 24x365
Index of size 24x365
I would like to create a matrix called "combined" of size 24x730
where the first column of combined is the first column of index followed by the first column of sorted_grid and so on
I have tried everything from loops, reshape to horzcat but I still have no solution and would appreciate any help.
Thank you!

채택된 답변

Davide Masiello
Davide Masiello 2022년 3월 9일
편집: Davide Masiello 2022년 3월 9일
You can do that using a for loop
clear,clc
sorted_grid = rand(24,365);
index = rand(24,365);
combined = [zeros(size(sorted_grid)),zeros(size(index))];
idx = 0;
for col = 1:2:2*size(sorted_grid,2)-1
idx = idx+1;
combined(:,col) = index(:,idx);
combined(:,col+1) = sorted_grid(:,idx);
end
EDIT:
More efficient and elegant code
clear,clc
sorted_grid = rand(24,365);
index = rand(24,365);
combined = [zeros(size(sorted_grid)),zeros(size(index))];
combined(:,1:2:end-1) = index;
combined(:,2:2:end) = sorted_grid;
  댓글 수: 3
Davide Masiello
Davide Masiello 2022년 3월 9일
No problem. Since I have edited it a couple of times, make sure that you are using the latest version (the one appearing while I am writing this comment).
Davide Masiello
Davide Masiello 2022년 3월 9일
Sorry, I edited it again adding a better solution using matrix indexing and getting rid of the for loop.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by