473,394 Members | 1,761 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

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(matrixa, nrow, mcol); // free memory
freematrix(matrixb, 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 4767
"Yudan Yi" <yi***@osu.edu> 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(double));

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(matrixa[i], matrixa[i]+mcol, matrixb[i]);

.. It's up to you to check which method is faster.
freematrix(matrixa, nrow, mcol); // free memory
freematrix(matrixb, 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(matrixa, nrow, mcol); // free memory
freematrix(matrixb, 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=(Matrix 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(matrixa, nrow, mcol); // free memory
freematrix(matrixb, 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_elem_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(matrixa, nrow, mcol); // free memory
freematrix(matrixb, 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
by: memocan | last post by:
#include <iostream> using namespace std; int x; //global variable matrix int main() { x= new float ; //initialize the size now }
4
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...
16
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...
11
by: bob | last post by:
Hi, given a vector of vectors of strings thus; typedef std::vector<std::string> product; typedef std::vector<product> product_matrix; whats the fastest, most efficient means of streaming...
8
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...
232
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...
0
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...
5
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...
3
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
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...

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.