how to form a two-column array for a given but dimmension-unknown array?

Dear All,
I have two array with the same length A and B. I want to form another array C which is formed by A and B. But the dimmensions of A and B are uncertain, sometimes A (B) is a row vector so that C = [A' B'], but sometimes A (B) is a column vector so that C = [A B].
I am wondering if there is a simple way to form array C without checking the dimmensions of A and B.
Thanks.
Benson

 Réponse acceptée

Stephen23
Stephen23 le 10 Juin 2021
Modifié(e) : Stephen23 le 10 Juin 2021
"I am wondering if there is a simple way to form array C without checking the dimmensions of A and B."
C = [A(:),B(:)]

Plus de réponses (1)

Joel Lynch
Joel Lynch le 9 Juin 2021
Modifié(e) : Joel Lynch le 10 Juin 2021
You can make a row vector of any N dimensional matrix by linearizing, for example
A( 1:numel(A), 1 ) = A(:);
.Thus, you can always make
C = C(1:numel(A),1:2) = [ A(:) , B(:) ];

4 commentaires

Hi, Joel,
I run your code. But the second C = C(1:numel(A),2) = [ A(:) , B(:) ] has the following error message:
Index exceeds array bounds.
Error in function_sub (line 506)
C = C(1:numel(A),2) == [ A(:) , B(:) ];
Thanks a lot.
Benson
Sorry, should be C(1:numel(A),1:2)=…
or more simply, C=…
I just included the indices so it was clear what size C would be.
I got the following error message again.
Error using horzcat
Dimensions of arrays being concatenated are not consistent.
Thanks.
Benson
Assuming A and B have the same number of elements, then C=[A(:),B(:)]; should work.
Make sure A, B, and C are cleared and reset before trying this. numel(A) and numel(B) should be the same. And C should not be defined.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Characters and Strings dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by