How to split the last 4 elements in a column into a new column?

조회 수: 1 (최근 30일)
Julia
Julia 2023년 2월 7일
댓글: Voss 2023년 2월 7일
If I have a column, say
5
7
2
3
6
4
9
and I want to split the first 3 elements and the last 4 elements into 2 column, like this,
5 3
7 6
2 4
9
Could anyone please tell me how I can do this? I thought about using reshape, but since my first column and second column do not have the same number of elements, reshape seems not applicable.

채택된 답변

Voss
Voss 2023년 2월 7일
M = [5; 7; 2; 3; 6; 4; 9]
M = 7×1
5 7 2 3 6 4 9
You can't use a matrix, like you said, because the lengths of the two new column vectors is not the same.
You could use a cell array:
C = {M(1:3) M(4:end)}
C = 1×2 cell array
{3×1 double} {4×1 double}
C{:} % show the contents of C
ans = 3×1
5 7 2
ans = 4×1
3 6 4 9
Or you can make two new variables, where each is a column vector:
M1 = M(1:3)
M1 = 3×1
5 7 2
M2 = M(4:end)
M2 = 4×1
3 6 4 9
  댓글 수: 2
Julia
Julia 2023년 2월 7일
Thank you so much! Why didn't I think about dividing them into new variables...

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

추가 답변 (2개)

Les Beckham
Les Beckham 2023년 2월 7일
편집: Les Beckham 2023년 2월 7일
I'm not sure why you want to do this, or what you intend to do with the results, but here is one possible way using a cell array.
A = [ ...
5
7
2
3
6
4
9];
B = {A(1:3), A(4:end)}
B = 1×2 cell array
{3×1 double} {4×1 double}
B{1}
ans = 3×1
5 7 2
B{2}
ans = 4×1
3 6 4 9

Constantino Carlos Reyes-Aldasoro
In Matlab is better to think of matrices than to think of columns (like you would do in Excel for instance), so think of your first column as a matrix
a= [5 7 2 3 6 4 9]'
a = 7×1
5 7 2 3 6 4 9
Then, if you want to "move" elements of that matrix (before you decide where) you need to use the address of those elements, e.g.
a(end-3:end)
ans = 4×1
3 6 4 9
That took the last four elements of the matrix. Now, where to move them, you can paste them into the second column of a, but the dimensions would not match directly, and also, you would need to remove those elements, which you only have selected, so better try a new matrix, and do one step at a time:
b(1:3,1) = a(1:3)
b = 3×1
5 7 2
b(1:4,2) = a(end-3:end)
b = 4×2
5 3 7 6 2 4 0 9
Notice that a zero was appended at the end of the first column. It would be same if you start adding elements beyond the existing ones, Matlab will complete the matrix, e.g.
b(6,4) = 11
b = 6×4
5 3 0 0 7 6 0 0 2 4 0 0 0 9 0 0 0 0 0 0 0 0 0 11
So, this would be a way to to split the last 4 elements in a column into a new column.

카테고리

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

태그

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by