473,703 Members | 2,323 Online

# matrix copy problem

I have a problem to copy (assign) a matrix to another matrix. Curreny, I
know copy the number using loops, while it will take some time, I wonder if
there have faster method. The following code explain my situation detailed.

double ** matrixa, **matrixb;
int nrow = 10, mcol = 10;
matrixa = initmatrix(nrow , mcol); // allocate memory a
matrixb = initmatrix(nrow , mcol); // allocate memory b
// copy a => b
for (int i=0;i<nrow;i++)
for (int j=0;j<mcol;j++)
matrixb[i][j] = matrixa[i][j];
freematrix(matr ixa, nrow, mcol); // free memory
freematrix(matr ixb, nrwo, mcol); // free memory
I want to find another way to copy the data from a => b without loop all the
data.

Thanks
Jul 23 '05 #1
4 4794
"Yudan Yi" <yi***@osu.ed u> wrote...
I have a problem to copy (assign) a matrix to another matrix. Curreny, I
know copy the number using loops, while it will take some time, I wonder if
there have faster method. The following code explain my situation detailed.

double ** matrixa, **matrixb;
int nrow = 10, mcol = 10;
matrixa = initmatrix(nrow , mcol); // allocate memory a
matrixb = initmatrix(nrow , mcol); // allocate memory b
// copy a => b
for (int i=0;i<nrow;i++)
for (int j=0;j<mcol;j++)
matrixb[i][j] = matrixa[i][j];
Without knowing what 'initmatrix' does, it's hard to be certain, but this

for (int i=0; i<nrow; i++)
memcpy(matrixb[i], matrixa[i], mcol*sizeof(dou ble));

could be just a bit faster. Of course, the real C++ way would be to use
'std::copy':

for (int i=0; i<nrow; i++)
std::copy(matri xa[i], matrixa[i]+mcol, matrixb[i]);

.. It's up to you to check which method is faster.
freematrix(matr ixa, nrow, mcol); // free memory
freematrix(matr ixb, nrwo, mcol); // free memory
I want to find another way to copy the data from a => b without loop all
the data.

See above. HTH

V
Jul 23 '05 #2
Yudan Yi wrote:
I have a problem to copy (assign) a matrix to another matrix. Curreny, I
know copy the number using loops, while it will take some time, I wonder
if there have faster method. The following code explain my situation
detailed.

double ** matrixa, **matrixb;
int nrow = 10, mcol = 10;
matrixa = initmatrix(nrow , mcol); // allocate memory a
matrixb = initmatrix(nrow , mcol); // allocate memory b
// copy a => b
for (int i=0;i<nrow;i++)
for (int j=0;j<mcol;j++)
matrixb[i][j] = matrixa[i][j];
freematrix(matr ixa, nrow, mcol); // free memory
freematrix(matr ixb, nrwo, mcol); // free memory
I want to find another way to copy the data from a => b without loop all
the data.

Thanks

For matrices, you are better off by far using a single array and addressing
it as matrix[ncols * i + j]. You get better data locality in the cache,
and you don't need a loop of malloc/new every time you want to make a copy.
With modern compilers & processors, the cost of the multiply is usually
either optimized away completely or irrelevant (a multiply is a cycle or
so, a memory lookup is at least a few, more likely a few dozen, cycles).
If you use something like BLAS (http://www.netlib.org/blas) to do the
underlying arithmetic, then even this cost disappears. Versus using nested
arrays requires an additional indirection which may be quite expensive.

Try wrapping this in a class as well, eg

class Matrix
{
public:
Matrix() : nrows_(0), ncols_(0), Data_(0) {}

Matrix(int nrows, int ncols) : nrows_(nrows), ncols_(ncols),
Data_(new double[nrows_ * ncols_]) {}

Matrix(Matrix const& Other) // fill in boring details
Matrix& operator=(Matri x const& Other); // fill in boring details

~Matrix() { delete[] Data_; }

double operator()(int i, int j) { return Data_[i * ncols + j]; }

// plus some functions to get the size, etc

private:
int nrows_, ncols_;
double* Data_;
};

With a bit of thought, you can do operator[] too, so you can use the 'old'
notation. Hint: return a pointer to the start of the row of the matrix.
But the operator() solution is easier, especially becuase it is trivial to
add some debug assert() statements to get bounds checking. That can
potentially save you an unbelievable amount of time, as can wrapping all of
the ugly memory management stuff inside a class.

By the way, for builtin types like double, you can use memcpy() to implement
the copy constructor and copy-assignment. Another advantage of the
single-array approach: you only need a single memcpy, versus a loop of them
for the multi-array approach. But don't do this for arrays of user-defined
types!

HTH,
Ian McCulloch

Jul 23 '05 #3
Yudan Yi wrote:
I have a problem to copy (assign) a matrix to another matrix. Curreny, I
know copy the number using loops, while it will take some time, I wonder if
there have faster method. The following code explain my situation detailed.

double ** matrixa, **matrixb;
int nrow = 10, mcol = 10;
matrixa = initmatrix(nrow , mcol); // allocate memory a
matrixb = initmatrix(nrow , mcol); // allocate memory b
// copy a => b
for (int i=0;i<nrow;i++)
for (int j=0;j<mcol;j++)
matrixb[i][j] = matrixa[i][j];
freematrix(matr ixa, nrow, mcol); // free memory
freematrix(matr ixb, nrwo, mcol); // free memory
I want to find another way to copy the data from a => b without loop all the
data.

Thanks

Use a matrix class ... (I posted the one below about a year ago)

#include <vector>

template <typename w_elem_type>
class matrix
{
public:
typedef int t_Size;

t_Size m_columns;
t_Size m_rows;

std::vector<w_e lem_type> m_data;

matrix( t_Size i_columns = 0, t_Size i_rows = 0 )
: m_columns( i_columns ),
m_rows( i_rows ),
m_data( i_columns * i_rows )
{
}

w_elem_type * operator[]( t_Size i_index )
{
return & ( m_data[ i_index * m_rows ] );
}

template <typename w_Type, int w_columns, int w_rows>
matrix( const w_Type (&i_array)[w_columns][w_rows] )
: m_columns( w_columns ),
m_rows( w_rows ),
m_data( & (i_array[0][0]), & (i_array[w_columns-1][w_rows]) )
{
}

};

#include <iostream>

double array[3][4] = {
{ 1.0, 2.0, 3.3, 4.4 },
{ 1.0, 2.0, 3.3, 4.4 },
{ 1.0, 2.0, 3.3, 4.5 },

};

int main()
{
matrix<float> mat1( 3, 4 );
matrix<float> mat2;
matrix<float> mat3( array );

mat2 = mat3;

std::cout << mat2[2][3] << "\n";
}
Jul 23 '05 #4
Yudan Yi wrote:
I have a problem to copy (assign) a matrix to another matrix. Curreny, I
know copy the number using loops, while it will take some time, I wonder if
there have faster method. The following code explain my situation detailed.

double ** matrixa, **matrixb;
int nrow = 10, mcol = 10;
matrixa = initmatrix(nrow , mcol); // allocate memory a
matrixb = initmatrix(nrow , mcol); // allocate memory b
// copy a => b
for (int i=0;i<nrow;i++)
for (int j=0;j<mcol;j++)
matrixb[i][j] = matrixa[i][j];
freematrix(matr ixa, nrow, mcol); // free memory
freematrix(matr ixb, nrwo, mcol); // free memory
I want to find another way to copy the data from a => b without loop all the
data.

Take a look at
The C++ Scalar, Vector, Matrix and Tensor class Library

http://www.netwood.net/~edwin/svmtl/

The Object Oriented Numerics Page

http://www.oonumerics.org/oon/

and Bjarne Stroustrup, "The C++ Programming Language: Third Edition",
Chapter 22 Numerics, Section 4 Vector Arithmetic,
Subsection 6 Slice_array, pages 671-5
Jul 23 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

### Similar topics

 6 6577 by: memocan | last post by: #include using namespace std; int x; //global variable matrix int main() { x= new float ; //initialize the size now } 4 21279 by: Harry | last post by: Hello, I am using a 2-dimensional matrix for image manipulation and recognition. The x-axes is image.width pixels long and the y-axes image.height. All fields have a RGB integer value. To store this value from the image into the matrix I am using the bitmap.getPixel(x,y) method because manipulating values in the matrix is much faster than using the bitmap.setPixel(x,y,color) method. My problem is, that the getPixel function is also very... 16 3265 by: Martin Jørgensen | last post by: Hi, I've made a program from numerical recipes. Looks like I'm not allowed to distribute the source code from numerical recipes but it shouldn't even be necessary to do that. My problem is that I'm not very experienced with pointers, pointers to pointers and the like and I got 4 compiler warnings + I don't completely understand how to build this "compact matrix" (see later). 11 1920 by: bob | last post by: Hi, given a vector of vectors of strings thus; typedef std::vector product; typedef std::vector product_matrix; whats the fastest, most efficient means of streaming the "product_matrix" to a file? I.E. without using two "for" or "while" 8 11042 by: lovecreatesbeauty | last post by: I write a function to rotate a matrix by 90 degrees clockwise, this function works on a matrix of specific size, for example, it rotates a 4*4 matrix of integers in the following code. The function makes one more copy of the original matrix, how is the efficiency? Can the copy be saved? Comments on it are welcome. Can I extend it to work on a matrix of any size (or even any type, not just integers) for the logic may be the same when it... 232 13281 by: robert maas, see http://tinyurl.com/uh3t | last post by: I'm working on examples of programming in several languages, all (except PHP) running under CGI so that I can show both the source files and the actually running of the examples online. The first set of examples, after decoding the HTML FORM contents, merely verifies the text within a field to make sure it is a valid representation of an integer, without any junk thrown in, i.e. it must satisfy the regular expression: ^ *?+ *\$ If the... 0 2809 by: DarrenWeber | last post by: # Copyright (C) 2007 Darren Lee Weber # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY... 5 9636 by: Anolethron | last post by: Wrong one: void minptr (int *matrix, int rows, int columns,int *min){ int i=0,j=0; *min=*matrix; //!!!!!!!!!!!!!!!!! for (i=0; i < rows; i++) { for (j=0; j < columns; j++) { if( *min *(matrix+(i*columns)+j) ) { min = (matrix+(i*columns)+j); 3 2210 by: craziileeboi | last post by: Hi I have been pulling my hair out trying to figure this out. Please help!!! Here is my project description: By using a pointer to pointers **A and **B and the function calloc() allocate the memory for the 4x4 matrices A and B. By using the pointers *a and *b and the function malloc() allocate the memory for the 4-dimensional vectors a and b. 0 8669 by: Hystou | last post by: Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,... 0 9121 by: jinu1996 | last post by: In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is... 0 8962 by: tracyyun | last post by: Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some... 0 7867 by: agi2029 | last post by: Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea... 1 6588 by: isladogs | last post by: The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will... 0 5922 by: conductexam | last post by: I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();... 0 4432 by: TSSRALBI | last post by: Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls... 0 4687 by: adsilva | last post by: A Windows Forms form does not have the event Unload, like VB6. What one acts like? 1 3123 by: 6302768590 | last post by: Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.