Hi,
What is the best way to merge several MathObject matrices into one MathObject matrix? In particular, I would like to be able to take several m x 1 matrices (i.e., "column vectors") and merge them into an m x n matrix.
Thanks!
Paul Pearson
If
$C1
and $C2
are the ColumnVectors, then
$M = Matrix($C1,$C2)->transpose;would do it. But if they are really two-dimensional matrices (like columns from another matrix), then use
$M = Matrix($C1->transpose,$C2->transpose)->transpose;to get the matrix with these columns.
Hope that does it for you.
Davide
Thanks Davide! That did help clarify what ought to be done.
I am using this inside a custom answer checker and noticed that when $C1->transpose was giving results with string representation like [[1,2,3]]. Since the outermost brackets in [[1,2,3]] were undesirable, I removed them using the ->row method:
$Row = Matrix($C1->transpose); $Row = $Row->row(1);
I put it all together into a little subroutine that takes in an array of column matrices and returns a single matrix comprised of those column matrices. Please let me know if anything in this subroutine needs improvement.
############################
sub put_cols_in_mtx {
my @c = @_;
my @temp = ();
for my $i (0..$#c) {
my $Row = Matrix($c[$i])->transpose; $Row = $Row->row(1);
push(@temp,$Row);
}
return Matrix(@temp)->transpose;
}
############################
Thanks!
Paul Pearson
I am using this inside a custom answer checker and noticed that when $C1->transpose was giving results with string representation like [[1,2,3]]. Since the outermost brackets in [[1,2,3]] were undesirable, I removed them using the ->row method:
$Row = Matrix($C1->transpose); $Row = $Row->row(1);
I put it all together into a little subroutine that takes in an array of column matrices and returns a single matrix comprised of those column matrices. Please let me know if anything in this subroutine needs improvement.
############################
sub put_cols_in_mtx {
my @c = @_;
my @temp = ();
for my $i (0..$#c) {
my $Row = Matrix($c[$i])->transpose; $Row = $Row->row(1);
push(@temp,$Row);
}
return Matrix(@temp)->transpose;
}
############################
Thanks!
Paul Pearson
It looks good. You could combine the line
my $Row = Matrix($c[$i])->transpose; $Row = $Row->row(1);into the single command
my $Row = Matrix($c[$i])->transpose->row(1);In fact, you could replace
my $Row = Matrix($c[$i])->transpose; $Row = $Row->row(1); push(@temp,$Row);with
push(@temp,Matrix($c[$i])->transpose->row(1));I guess you could also simplify the loop slightly as
for my $c (@c) { push(@temp,Matrix($c)->transpose->row(1)); }since you can iterate over your column array. Technically, you could also reuse
@c
by setting
for my $c (@c) {$c = Matrix($c)->transpose->row(1)} return Matrix(@c)->transpose;rather than allocating a second array, but perhaps that is too much.
Other than that, it looks fine.
Davide