How can i form a matrix out of n number of different column matrices of same size by placing them side by side.

 Akzeptierte Antwort

Dave B
Dave B am 13 Nov. 2021
Bearbeitet: Dave B am 13 Nov. 2021
You can make append two columns like this:
a=rand(10,1);
b=rand(10,1);
c=[a b];
size(c)
ans = 1×2
10 2
or like this:
c=cat(2,a,b);
size(c)
ans = 1×2
10 2
Both approaches extend to n columns:
a=rand(10,1);
b=rand(10,1);
c=rand(10,1);
d=rand(10,1);
M1=[a b c d];
size(M1)
ans = 1×2
10 4
M2=cat(2,a,b,c,d);
size(M2)
ans = 1×2
10 4
Alternatively, you could initialize a matrix and then fill it with the columns:
M3=nan(numel(a),4); % you don't really need to initialize, but it is wise
M3(:,1) = a;
M3(:,2) = b;
M3(:,3) = c;
M3(:,4) = d;
size(M3)
ans = 1×2
10 4

6 Kommentare

HEMRAJ PATEL
HEMRAJ PATEL am 13 Nov. 2021
Can you please explain it using for loop as i have n no. of column matrices. My n extends to 2000.
Image Analyst
Image Analyst am 13 Nov. 2021
@HEMRAJ PATEL surely they don't all have unique names though. You don't have 2000 separately named individual variables do you, because that would be a disaster.
HEMRAJ PATEL
HEMRAJ PATEL am 13 Nov. 2021
In case of
c=cat(2,a,b);
size(c);
if i have 2000 matrices like (c1,c2,c3,...,c2000) and i want them in cat function.
How will i do it.
Do i have to write c=cat(2,c1,c2,c3....) or do we have another option
Dave B
Dave B am 13 Nov. 2021
Bearbeitet: Dave B am 13 Nov. 2021
Where do c1, c2, etc come from? Can you create them as a matrix to begin with? How are they identified? is it all variables in the workspace that begin with the letter c?
In theory, you could create a statement like the one above using eval...but as @Image Analyst if you have 2000 separately named variables that sounds like a disaster, and if you're using the variable name to indicate column identity that's probably also not great.
Stephen23
Stephen23 am 13 Nov. 2021
"if i have 2000 matrices like (c1,c2,c3,...,c2000) and i want them in cat function. How will i do it."
I have some ideas of how you might do it, but no experienced MATLAB users would do that.
"Do i have to write c=cat(2,c1,c2,c3....) or do we have another option"
Another option is better data design: don't have numbered variable names.
Numbered variable names is a sign that you are doing something wrong. Use indexing instead.
HEMRAJ PATEL
HEMRAJ PATEL am 13 Nov. 2021
Thanks for your valuable replies. I have solved my problem, i might have framed my question wrong.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Produkte

Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by