Консультация № 145814
02.10.2008, 19:21
0.00 руб.
0 2 2
Добрый вечер уважаемые специалисты. Очень сильно нужна ваша помощь в решении проблемы.
Подскажите код программы - матричный калькулятор (MxN). Который умножает, складывает и вычитает две матрицы. Заранее благодарю!

Обсуждение

Неизвестный
02.10.2008, 20:01
общий
02.10.2008, 20:32
это ответ
Здравствуйте, Ютанова!
Код операций с матрицами в приложении. Если не понятен алгоритм умножения, смотрите вопрос 145194.
Цитата: из вопроса №145194
У меня вопросик маленький или прозьба нужен алгоритм "Умножение матрицы на матрицу " если есть пришлите на covalijenia@mail.ru
Я предумал свой алгоритм но он дает ошибки после каждой строки в приложение Описание класса MATRIX и функция сложения
" MATRIX * Multiplication_matrixes_on_a_matrix ( MATRIX * , int , int ); "
Отправил: Covalijenia, Посетитель
Дата отправки: 27.09.2008, 13:40
Поступило ответов: 1
Состояние: В очереди (до окончания - менее суток)
Приложение:
Код:
class MATRIX                                    /* Definition of a class the Matrix  */
{
private: /* The limited access */

float * * The_index_on_float; /* The index on the type index float */
int Quantity_of_lines; /* Quantity of lines */
int Quantity_of_columns; /* Quantity of columns */
int Error_code; /* Error_code */

public: /* The general access */

MATRIX ( int , int ); /* The designer with two parametres 'Rectangular matrix' */
~MATRIX ( ); /* The undesigner */

MATRIX * Information_Input ( MATRIX * , int , int ); /* The funcion 'Information_Input'*/
Conclusion_to_the_element_screen ( MATRIX *, int , int );/* The funcion 'Conclusion_to_the_element_screen'*/
Definition_of_value_of_an_element_i_j ( MATRIX * , int , int );/* The funcion 'Definition_of_value_of_an_element_i_j'*/
MATRIX * Multiplication_of_a_matrix_to_number ( MATRIX * , int , int );/* The funcion 'Multiplication_of_a_matrix_to_number'*/
MATRIX * Subtraction_matrixes_with_a_matrix ( MATRIX * , int , int );/* The funcion 'Subtraction_matrixes_with_a_matrix'*/
MATRIX * Multiplication_matrixes_on_a_matrix ( MATRIX * , int , int );/* The funcion 'Multiplication_matrixes_on_a_matrix'*/
MATRIX * Addition_matrixes_with_a_matrix ( MATRIX * , int , int );/* The funcion 'Addition_matrixes_with_a_matrix'*/
MATRIX * Memory_removal ( MATRIX * , int , int );/* The funcion 'Memory_removal'*/
};
MATRIX * MATRIX :: Multiplication_matrixes_on_a_matrix ( MATRIX * INDEX , int size_lines , int size_columns )/* The funcion 'Subtraction_matrixes_with_a_matrix'*/
{
int Quantity_of_lines = 0, Quantity_of_columns = 0;/* declare a variable */
cout <<" Enter size of struct 'MATRIX', Quantity_of_lines: ";/* The message to the user */
cin >> Quantity_of_lines; /* Information Input */
cout <<" Enter size of struct 'MATRIX', Quantity_of_columns: ";/* The message to the user */
cin >> Quantity_of_columns; /* Information Input */
float * * The_index_on_float; /* The index on the type index float */
The_index_on_float = new float * [ Quantity_of_lines ];/* Allocation of a file of indexes on type indexes float */
( The_index_on_float ) ? cout << " Memory has been allocated for a array of indexes of type float COLUMNS'size-"<< size_lines << "';" : cout << "Memory was not allocated;" << endl;/* The control over memory*/
for ( int i = 0; i < Quantity_of_lines; i++ ) /*The cycle beginning*/
{
The_index_on_float [ i ] = new float [ Quantity_of_columns ];/* Allocation of files of type float */
( The_index_on_float [ i ] ) ?cout << " Memory has been allocated for a type array float LINES'size-" << size_columns << "';" << " From COLOMN: "<< i + 1 << endl : cout << "Memory was not allocated;" <<endl;/* The control over memory*/
}
for ( i = 0; i < Quantity_of_lines; i++ ) /*The cycle beginning*/
{
for ( int j = 0; j < Quantity_of_columns; j++ )/*The cycle beginning*/
{
cout << " Please Enter your MATRIX [ " << i + 1 << " ] [ " << j + 1 << " ] : ";/* The message to the user */
cin >> The_index_on_float [ i ] [ j ];/* Data input*/
}
}
INDEX -> Conclusion_to_the_element_screen ( INDEX , size_lines , size_columns ); /*To apply function */

cout << " Conclusion to the element screen: " << endl << endl;/* The message to the user */
for ( i = 0; i < Quantity_of_lines; i++ )/*The cycle beginning*/
{
cout << " ";/* The message to the user */
for ( int j = 0; j < Quantity_of_columns; j++ )/*The cycle beginning*/
{
cout << " " << The_index_on_float [ i ] [ j ];/* The message to the user */
}
cout << endl << endl; /* The message to the user */
}
for ( i = 0; i < size_lines; i++ ) /*The cycle beginning*/
{
for ( int j = 0; j < Quantity_of_columns; j++ )/*The cycle beginning*/
{
for ( int z = 0; z < Quantity_of_lines; z++ )/*The cycle beginning*/
{
if ( z == 0 ) /*The control of memory */
{
INDEX -> The_index_on_float [ i ] [ j ]= INDEX -> The_index_on_float [ i ] [ z ] * The_index_on_float [ z ] [ j ];/*Multiplication*/
}
else
{
INDEX -> The_index_on_float [ i ] [ j ] =INDEX -> The_index_on_float [ i ] [ j ] + ( INDEX -> The_index_on_float [ i ] [ z ] * The_index_on_float [ z ] [ j ] );/*Multiplication*/
}
}
}
}
cout << " Conclusion to the element screen: " << endl << endl;/* The message to the user */
for ( i = 0; i < size_lines; i++ ) /*The cycle beginning*/
{
cout << " ";/* The message to the user */
for ( int j = 0; j < Quantity_of_columns; j++ )/*The cycle beginning*/
{
cout << " "<< INDEX -> The_index_on_float [ i ] [ j ] ;/* The message to the user */
}
cout << endl << endl; /* The message to the user */
}
for ( i = 0; i < size_lines; i++ ) /*The cycle beginning*/
{
delete [ ] The_index_on_float [ i ]; /*delete*/
}
delete [ ] The_index_on_float; /*delete*/
return INDEX;
}


Ответ № 1 от realbustard, 3-ий класс
Здравствуйте, Covalijenia!
В приложении код, использующий ф-у умножения матриц, которую ,в принципе, можно оптимизировать, например сделав меньшее количество аргументов. Но остановимся на алгоритме ее работы. Она получает 3 указателя на матрицы: А,В-множители; С-результат; m1..n2-размеры матриц А,В. Перед присваиванием матрице определенного значения, число, находящееся по адресу этого элемента С[i][j] обнуляется, чтоб мы были уверены, что там ноль, а не что иное. Ну что сначала цикл по i, затем по j, это объяснять не надо.
А вот на цикле по k остановлюсь.
Каждый элемент результирующей матрицы складывается из суммы произведений элементов 2х матриц, например, если A[2][2] и B[2][2], то
С[0][0]=A[0][0]*B[0][0]+A[0][1]*B[1][0]; С[0][1]=A[0][0]*B[0][1]+A[0][1]*B[1][1];
С[1][0]=A[1][0]*B[0][0]+A[1][1]*B[1][0]; С[1][1]=A[1][0]*B[0][1]+A[1][1]*B[1][1];
Можно заметить, что некоторые значения i и j в многочлене совпадают со значениями i,j в теле цикла, а некоторые отличаются на 1 от них, т.е. можно записать так:
C[i][j]=A[i][?]*B[?][j]+A[i][?]*B[?][j]; где: i,j - переменные значения которых, совпадают со значениями i,j в C[i][j];
Знак вопроса - это число, которое увеличивается от 0 до (n1-1) и оно равно числу членов в многочлене, в данном случае 2.
Если подставить вместо ? к, то получим:
C[i][j]=A[i][k]*B[k][j]+A[i][k+1]*B[k+1][j];
Чтобы проще посчитать С[i][j] и был введен 3й цикл по к
Общий вид многочлена принял вид:
C[i][j]=Сумма_по_k (A[i][k]*B[k][j]) ); где к==0...(n1-1)
//k - это итератор, равный n1 и m2.
for(int k=0;k<n1;k++){
C[i][j]+=A[i][k]*B[k][j];
}
Приложение:
Код:
#include <iostream>

//Подключаются для заполнения массива случайными значениями
#include <time.h>
#include <stdlib.h>


using namespace std;

//Функция, в которой происходит умножение матриц
//В качестве аргументов получает указатели на массивы указателей(наши матрицы)
//и размеры матриц(m1..n2)
void mult(int** A,int** B,int **C,int m1,int m2,int n1,int n2);

int main()
{
srand(time(NULL));

//Задаем размеры первой матрицы
int m1,n1;
cout<<"BBEDuTE PA3MEPHOCTb MATPuCbI A: ";
cin>>m1>>n1;
cout<<endl;

//Задаем размеры второй матрицы
int m2,n2;
cout<<"BBEDuTE PA3MEPHOCTb MATPuCbI B: ";
cin>>m2>>n2;
cout<<endl;

//Если количество столбцов первой матрицы равно количеству строк второй матрицы
//и все числа положительны, происходит создание матриц
if((n1==m2)&(m1>0)&(m2>0)&(n1>0)&(n2>0)){

//Массив указателей А - первая матрица
int** A=new int*[m1];

//Создание, заполнение случайными значениями и вывод на экран
for (int i=0;i<m1;i++){
A[i]=new int[n1];
for (int j=0;j<n1;j++){
A[i][j]=rand()%10-5;
cout<<A[i][j]<<"\t";
}
cout<<endl;
}

cout<<endl;

//Массив указателей B - вторая матрица
int** B=new int*[m2];

for (int i=0;i<m2;i++){
B[i]=new int[n2];
for (int j=0;j<n2;j++){
B[i][j]=rand()%10-5;
cout<<B[i][j]<<"\t";
}
cout<<endl;
}

cout<<endl;

//Матрица С - резулитат умножения А х В
int** C=new int*[m1];

//Используем функцию умножения
mult(A,B,C,m1,m2,n1,n2);

//Если убрать комментарии, указатель p можно использовать
//для вывода на экран матрицы С.

//int** p=C;

/*//Вывод массива
for(int i=0; i<m1; i++){
for (int j=0;j<n2;j++){
cout<<p[i][j]<<"\t";
}
cout<<endl;
}
cout<<endl;*/


//Освобождение памяти
for(int i=0; i<m1; i++){
delete [] A[i];
}

for(int i=0; i<m2; i++){
delete [] B[i];
}

for(int i=0; i<m2; i++){
delete [] C[i];
}

//delete p;
}

else
cout<<"BBeDEHbI HEIIPABuJIbHbIE PA3MEPbI MATPuC\n";

return 0;
}

void mult(int** A,int** B,int** C,int m1,int m2,int n1,int n2)
{
//Заполнение матрицы С
for(int i=0;i<m1;i++){
C[i]=new int[n2];
for(int j=0;j<n2;j++){
//Перед тем, как будет получено очередное значение элемента С[i][j],
// ему надо присвоить значение нуля, иначе будет любое другое ненулевое значение
C[i][j]=0;

//k - это итератор, равный n1 и m2.
for(int k=0;k<n1;k++){
C[i][j]+=A[i][k]*B[k][j];
}
//Печать элемента
cout<<C[i][j]<<"\t";
}
cout<<endl;
}

}

Ответил: realbustard, 3-ий класс
Дата отправки: 28.09.2008, 00:56

[27.09.2008, 14:20]
Первая ссылка в google на запрос c++ matrix class :
© Цитата:
Matrix C++ template class library with full source code
- [ Перевести эту страницу ]
Matrix template class library for performing matrix algebra calculations in C++ programs for engineering / scientific works in easy and efficient manner.
www.techsoftpl.com/matrix/index.htm
А в том что вы написали, разобраться трудно.
Хватов Сергей, Практикант


Приложение:
#include <iostream>

//Подключаются для заполнения массива случайными значениями
#include <time.h>
#include <stdlib.h>


using namespace std;

//Функции, в которых происходят арифметические действия над матрицами
//В качестве аргументов получают указатели на массивы указателей(наши матрицы)
//и размеры матриц(m1..n2)
void mult(int** A,int** B,int** C,int m1,int m2,int n1,int n2);
void plus(int** A,int** B,int** D,int m1,int m2,int n1,int n2);
void minus(int** A,int** B,int** E,int m1,int m2,int n1,int n2);

int main()
{
srand(time(NULL));

//Задаем размеры первой матрицы
int m1,n1;
cout<<"BBEDuTE PA3MEPHOCTb MATPuCbI A: ";
cin>>m1>>n1;
cout<<endl;

//Задаем размеры второй матрицы
int m2,n2;
cout<<"BBEDuTE PA3MEPHOCTb MATPuCbI B: ";
cin>>m2>>n2;
cout<<endl;

/*УМНОЖЕНИЕ*/

//Если количество столбцов первой матрицы равно количеству строк второй матрицы
//и все числа положительны, происходит создание матриц
if((n1==m2)&(m1>0)&(m2>0)&(n1>0)&(n2>0)){

//Массив указателей А - первая матрица
int** A=new int*[m1];

//Создание, заполнение случайными значениями и вывод на экран
cout<<"MATPuCA A:\n";
for (int i=0;i<m1;i++){
A[i]=new int[n1];
for (int j=0;j<n1;j++){
A[i][j]=rand()%10-5;
cout<<A[i][j]<<"\t";
}
cout<<endl;
}

cout<<endl;

//Массив указателей B - вторая матрица
cout<<"MATPuCA B:\n";
int** B=new int*[m2];

for (int i=0;i<m2;i++){
B[i]=new int[n2];
for (int j=0;j<n2;j++){
B[i][j]=rand()%10-5;
cout<<B[i][j]<<"\t";
}
cout<<endl;
}

cout<<endl;

//Матрица С - резулитат умножения А х В
int** C=new int*[m1];

//Используем функцию умножения
cout<<"YMHO]|[EHuE MATPuC:\n\n";
mult(A,B,C,m1,m2,n1,n2);

/*СЛОЖЕНИЕ И ВЫЧИТАНИЕ*/

//Если матрицы имеют одинаковую размерность
//то выполняются действия

if ((m1==m2)&&(n1==n2)){
int** D=new int*[m1];
int** E=new int*[m1];

cout<<endl<<"CJIO]|[EHuE MATPIC:\n\n";
plus(A,B,D,m1,m2,n1,n2);

cout<<endl<<"PA3HuUA MATRIC:\n\n";
minus(A,B,E,m1,m2,n1,n2);
cout<<endl;


//Очистка памяти
for(int i=0; i<m2; i++){
delete [] D[i];
}

for(int i=0; i<m2; i++){
delete [] E[i];
}

}
else
cout<<"BBeDEHbI HEIIPABuJIbHbIE PA3MEPbI MATPuC\n";

cout<<endl;


//Освобождение памяти
for(int i=0; i<m1; i++){
delete [] A[i];
}

for(int i=0; i<m2; i++){
delete [] B[i];
}

for(int i=0; i<m2; i++){
delete [] C[i];
}

}

else
cout<<"BBeDEHbI HEIIPABuJIbHbIE PA3MEPbI MATPuC\n";

return 0;
}

void mult(int** A,int** B,int** C,int m1,int m2,int n1,int n2)
{
//Заполнение матрицы С
for(int i=0;i<m1;i++){
C[i]=new int[n2];
for(int j=0;j<n2;j++){
//Перед тем, как будет получено очередное значение элемента С[i][j],
// ему надо присвоить значение нуля, иначе будет любое другое ненулевое значение
C[i][j]=0;

//k - это итератор, равный n1 и m2.
for(int k=0;k<n1;k++){
C[i][j]+=A[i][k]*B[k][j];
}
//Печать элемента
cout<<C[i][j]<<"\t";
}
cout<<endl;
}

}

void plus(int** A,int** B,int** D,int m1,int m2,int n1,int n2)
{
for(int i=0;i<m1;i++){
D[i]=new int[n2];
for(int j=0;j<n2;j++){

D[i][j]=A[i][j]+B[i][j];
//Печать элемента
cout<<D[i][j]<<"\t";
}
cout<<endl;
}
}


void minus(int** A,int** B,int** E,int m1,int m2,int n1,int n2)
{
for(int i=0;i<m1;i++){
E[i]=new int[n2];
for(int j=0;j<n2;j++){

E[i][j]=A[i][j]-B[i][j];
//Печать элемента
cout<<E[i][j]<<"\t";
}
cout<<endl;
}
}
Неизвестный
06.10.2008, 00:48
общий
это ответ

Здравствуйте, [b]Ютанова[/b]!


В приложении находится текст файла matrix.h (содержит шаблон класса Matrix<Type>).
Создавать матрицу можно тремя способами:
  • Matrix(const size_t &rows, const size_t &cols);
    rows, cols - количество строк и столбцов в матрице
  • Matrix(const Matrix<T> &mx);
    mx - другая матрица того же типа
  • Matrix(const T *const mx
  • [], const size_t &rows, const size_t &cols);
    mx - двумерный массив, rows, cols - его размеры (количество строк и столбцов)

Обращаться к элементам матрицы можно как к обычному двухмерному массиву:
  • Matrix<int> mx(10,10);
    mx
  • [5][3] = 15;

Умножение производится как на число, так и на другую матрицу. Для этого имеются:
  • функция mul
  • оператор *
  • оператор *=

Сложение и вычитание производится только с матрицами того же размера, что и исходная:
  • функции add() и sub()
  • операторы + и -
  • операторы += и -=


Пример использования (main.cpp):
Код:
#include <iostream>
#include "matrix.h"

using namespace std;

int main ()
{
// Матрица А
const int A1[] = {2, 3};
const int A2[] = {1, 0};
const int A3[] = {-1, 3};
const int *const mxA[] = {A1, A2, A3};

// Матрица Б
const int B1[] = {2, 0, 1};
const int B2[] = {1, -2, 2};
const int B3[] = {5, 0, 7};
const int *const mxB[] = {B1, B2, B3};

Matrix<int> a(mxA, 3, 2);
cout << "a = \n";
a.print();

Matrix<int> b(mxB, 3, 3);
cout << "b = \n";
b.print();

// Умножение числа на матрицу, матрицы на матрицу и вычитание
// Результат заносится в матрицу С
Matrix<int> c = (2*a) - (b*a);
// Ответ:
// 1, -3
// 4, -9
// -5, -30
cout << "\nc = 2a - ba = \n";
// Выводим результат
c.print();

return 0;
}

Удачи!

Приложение:
#ifndef MATRIX_H
#define MATRIX_H

#include <algorithm>
#include <iterator>
#include <vector>
#include <ostream>
#include <functional>

template <typename T>
class Matrix
{
public:
Matrix(const size_t &rows, const size_t &cols) : __arr(rows*cols), __rows(rows), __cols(cols) {};
Matrix(const Matrix<T> &mx) : __arr(mx.__arr.begin(), mx.__arr.end()), __rows(mx.__rows), __cols(mx.__cols) {};
Matrix(const T *const mx[], const size_t &rows, const size_t &cols) : __arr(rows*cols), __rows(rows), __cols(cols)
{
size_t i;
for (i = 0; i < __rows; ++i)
std::copy(mx[i],
mx[i]+cols,
__arr.begin() + cols*i);
};
Matrix& operator=(const Matrix<T>&);

class Error {};
class EOutOfIndex : public Error {};
class ESizeMissmatch : public Error {};

// Ряд матрицы
// ############################
class MatrixRow
{
public:
MatrixRow(T* begin, const size_t &size) : __begin(begin), __size(size) {};
T& operator[](const size_t &index) { return *(__begin+index); };
const T& operator[](const size_t &index) const { return *(__begin+index); };
T& at(const size_t &index)
{
if (__size <= index) throw EOutOfIndex();
return *this[index];
};
const T& at(const size_t &index) const
{
if (__size <= index) throw EOutOfIndex();
return *this[index];
};
private:
T* __begin;
size_t __size;
};
// ############################

// Специальный функтор для перемножения матриц
// ############################
class RowMul : public std::binary_function<const T&, const T&, T>
{
public:
explicit RowMul(const T& val) : __val(val) {};
T operator()(const T &lhs, const T &rhs) { return (lhs + rhs*__val); };
private:
T __val;
};
// ############################

MatrixRow operator[](const size_t &row) { return MatrixRow(&__arr[row*__cols], __cols); };
const MatrixRow operator[](const size_t &row) const { return MatrixRow(&__arr[row*__cols], __cols); };

MatrixRow at(const size_t &index)
{
if (__rows <= index) throw EOutOfIndex();
return *this[index];
};
const MatrixRow at(const size_t &index) const
{
if (__rows <= index) throw EOutOfIndex();
return *this[index];
};

// Умножение на число
// ############################
Matrix& mul(const T &mulTo)
{
std::transform(__arr.begin(), __arr.end(), __arr.begin(),
std::bind2nd(std::multiplies<T>(), mulTo));
return *this;
};
Matrix& operator*=(const T &mulTo)
{
return mul(mulTo);
};

// Умножение на матрицу
// ############################
Matrix& mul(const Matrix<T>&);
Matrix operator*(const Matrix<T> &mx) const { return Matrix<T>(*this).mul(mx); };
Matrix& operator*=(const Matrix<T> &mx) { return mul(mx); };

Matrix operator-() const
{
Matrix<T> __result(*this);
std::transform(__arr.begin(), __arr.end(), __result.__arr.begin(),
std::bind1st(std::minus<T>(), T(0)));
return __result;
};

// Сложение
// ############################
Matrix& add(const Matrix<T> &mx)
{
if ((mx.__rows != __rows) || (mx.__cols != __cols)) throw ESizeMissmatch();
std::transform(__arr.begin(), __arr.end(), mx.__arr.begin(), __arr.begin(),
std::plus<T>());
return *this;
};
Matrix& operator+=(const Matrix<T> &mx) { return add(mx); };
Matrix operator+(const Matrix<T> &mx) const { return Matrix<T>(*this).add(mx); };

// Вычитание
// ############################
Matrix& sub(const Matrix<T> &mx)
{
if ((mx.__rows != __rows) || (mx.__cols != __cols)) throw ESizeMissmatch();
std::transform(__arr.begin(), __arr.end(), mx.__arr.begin(), __arr.begin(),
std::minus<T>());
return *this;
};
Matrix& operator-=(const Matrix<T> &mx) { return sub(mx); };
Matrix operator-(const Matrix<T> &mx) const { return Matrix<T>(*this).sub(mx); };

// Вывод в поток (по умолчанию - в консоль)
// ############################
void print(std::ostream &out = std::cout) const
{
size_t i;
for (i = 0; i < __rows; ++i)
{
std::copy(__arr.begin()+ __cols*i, __arr.begin() + __cols*(i + 1) - 1,
std::ostream_iterator<T>(out, ", "));
out << *(__arr.begin() + __cols*(i + 1) - 1) << std::endl;
}
};

private:
std::vector<T> __arr;
size_t __rows, __cols;
};

// Умножение на число
// ############################
template <typename T>
Matrix<T> operator*(const Matrix<T> &lhs, const T &rhs)
{
return Matrix<T>(lhs).mul(rhs);
}

// Умножение числа на матрицу
// ############################
template <typename T>
Matrix<T> operator*(const T &lhs, const Matrix<T> &rhs)
{
return Matrix<T>(rhs).mul(lhs);
}

// Оператор присваивания
// ############################
template <typename T>
Matrix<T>& Matrix<T>::operator=(const Matrix<T> &mx)
{
if (&mx == this) return *this;
__arr.resize(mx.__arr.size());
std::copy(mx.__arr.begin(), mx.__arr.end(), __arr.begin());
__rows = mx.__rows;
__cols = mx.__cols;
return *this;
}

// Умножение матрицы на матрицу
// ############################
template <typename T>
Matrix<T>& Matrix<T>::mul(const Matrix<T> &mx)
{
// Ошибка
if (__cols != mx.__rows) throw ESizeMissmatch();
typedef typename std::vector<T> VecT;
typedef typename VecT::iterator VIter;
VecT __result(mx.__cols*__rows);
VIter __start(__result.begin()), __end(__result.end());
VIter __jarr(__arr.begin());

typename VecT::const_iterator __jmxarr, __jend(mx.__arr.end());

// Перемножение по рядам
while (__start != __end)
{
// Переходим в начало второй матрицы
__jmxarr = mx.__arr.begin();
// Перебираем вторую матрицу по строкам,
// первую - по элементам
while (__jmxarr != __jend)
{
// Умножение и сумму выполняет класс RowMul
std::transform(__start, __start + mx.__cols, __jmxarr,
__start, RowMul(*__jarr));
// Следующая строка второй матрицы
__jmxarr += mx.__cols;
// Следующий элемент первой матрицы
++__jarr;
}
// Переходим к следующей строке результата
__start += mx.__cols;
}

// Перемещаем результат в собственный вектор
__arr.swap(__result);
// Устанавливаем новое количество столбцов
__cols = mx.__cols;

return *this;
}

#endif // MATRIX_H
Форма ответа