Hi,
Say I have a 5 by 2 matrix in the form:
A = [2 5; 9 7; 10 2; 3 2; 1 9]
A = 5×2
2 5 9 7 10 2 3 2 1 9
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
And I want to make a 10 by 1 matrix from these values so that I get:
B = [2;5;9;7;10;2;3;2;1;9]
B = 10×1
2 5 9 7 10 2 3 2 1 9
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
How would I do this?
I know there is a probably a simple fix, but I haven't been able to do it.
Many thanks,
Scott

 채택된 답변

Matt J
Matt J 2025년 8월 1일

0 개 추천

A = [2 5; 9 7; 10 2; 3 2; 1 9];
B([1:2:10,2:2:10],1)=A(:)
B = 10×1
2 5 9 7 10 2 3 2 1 9
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

댓글 수: 3

dpb
dpb 2025년 8월 1일
편집: dpb 2025년 8월 2일
Good illustration of MATLAB indexing operations...more of the same
A = [2 5; 9 7; 10 2; 3 2; 1 9];
B=cell2mat(arrayfun(@(r)cat(1,A(r,:).'),1:height(A),'UniformOutput',false).')
B = 10×1
2 5 9 7 10 2 3 2 1 9
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
isOdd=@(i)mod(i,2)==1;
B=nan(numel(A),1);
B(isOdd(1:numel(B)))=A(:,1);
B(~isOdd(1:numel(B)))=A(:,2)
B = 10×1
2 5 9 7 10 2 3 2 1 9
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
B=accumarray([1:2:numel(A) 2:2:numel(A)].',A(:))
B = 10×1
2 5 9 7 10 2 3 2 1 9
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
<lol>
Scott Banks
Scott Banks 2025년 8월 2일
Thanks, guys
dpb
dpb 2025년 8월 2일
@Scott Banks, you're free to choose the solution you wish, but I'm curious why you chose the direct indexing solution over the generic one?
As I noted, it does illustrate using vectors as indices in MATLAB which is a powerful tool/feature and is sometimes invaluable, but the other code is general for any size array rather than only working for the specific case and more difficult to code generically (as my other tongue-in-cheek examples illustrate).
Again, just wondering what was your thinking here? Did my response need more amplification beyond the comments?

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

추가 답변 (1개)

dpb
dpb 2025년 8월 1일
편집: dpb 2025년 8월 1일

2 개 추천

A = [2 5; 9 7; 10 2; 3 2; 1 9];
% option A
B=A.'; B=B(:) % B=A.'(:); is invalid MATLAB syntax, unfortunately. (Octave allows this in at least some contexts)
B = 10×1
2 5 9 7 10 2 3 2 1 9
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
% option B
B=reshape(A.',[],1) % how to implement the above wanted but unallowable syntax...
B = 10×1
2 5 9 7 10 2 3 2 1 9
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
The key is to recognize need to transpose to get in needed/wanted column order first...

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

질문:

2025년 8월 1일

댓글:

dpb
2025년 8월 2일

Community Treasure Hunt

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

Start Hunting!

Translated by