# how to copy matrices

• 02-12-2003
jverkoey
how to copy matrices
how can you copy one 30x30 matrix in to another?

something like this (i know this doesn't work)

int a1[30] [30];
int a2[30] [30];

a1=a2;

but, yah, if you get what i mean
• 02-12-2003
grib
memcpy(a1,a2,sizeof(a1));

note that sizeof(a1) == sizeof(a2) and this only works for plain old data (ints, floats, etc..). You must include <string.h> (or <cstring> and use std::memcpy)
• 02-12-2003
lithium
i think you would need to overload the = operator : )
what i think you overload it so that it traverses one matrix (with two for loops) and copies the current value to that of another matrix
• 02-12-2003
nextus
um write a for loop?..actually two for loops

for(int i = 0; i < 30; i++)
{
for(int j = 0; j < 30; j++)
{
a2[i][j] = a1[i][j];
}
}

something like that.. :)
• 02-12-2003
lithium
i said two for loops
• 02-12-2003
nextus
oops when i wrote that i saw 0 replies..sorry slow typer...and all credits to lithium...
• 02-12-2003
jverkoey
lol, no duh, for loops are an easy way out, lol

however, it's incredibly slow that way if you have a big matrix

I was looking for the most EFFICIENT way of doing it
• 02-12-2003
nextus
how big of a matrix? and have you looked at the matrix header file...i think they use the for loop to copy....because at my school we use the vector header file...even though i wrote my own to understand what it is doing
• 02-12-2003
grib
The most efficent way of doing it is to look for a way to not make the copy in the first place, barring that memcpy is usually as well optimized as you are likely to see. To go faster you have to start looking at really tweaky assembly language tricks that are almost never worth your time, unless you are shaving cycles purely for the fun of it.