Как найти произведение элементов в каждом столбце

Orion6767

2 / 2 / 1

Регистрация: 26.10.2010

Сообщений: 67

1

Для каждого столбца матрицы найти произведение его элементов.

22.05.2011, 17:11. Показов 13350. Ответов 2

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Дана матрица размера M × N. Для каждого столбца матрицы найти произведение его элементов.

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <time.h>
 
using namespace std;
 
int main()
 
{
        int i, j, n, m, p;
    p=1;
    srand (time(NULL));
    cout<<"n = "; cin>>n;
    cout<<"m = "; cin>>m;
    int** a=new int* [n]; 
    for(i=0;i<n;i++) a[i]=new int [m]; 
    cout<<"Matrix"<<endl;
    for(i=0;i<n;i++)
    {
    for(j=0;j<m;j++)
    {
    a[i][j]=rand()%20;
    cout<<"  "<<a[i][j];  
    }
    cout<<endl;
    }
    {
    for(i=0;i<n;i++)
    {
    for(j=0;j<m;j++)
    {
    p*=a[j][i];
    }
    cout<<p<<endl;
    }
    return 0;
}
}

Я начал делать но у меня проблема с циклом, он не считает каждый столбец отдельно, что нужно изменить чтобы он считал произведение каждого столбца? Сейчас он умножает найденное произведение с произведением следующего столбца и т.д.



0



-comrade-

364 / 365 / 167

Регистрация: 11.06.2010

Сообщений: 703

22.05.2011, 17:24

2

Orion6767, так?

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
 
using namespace std;
 
int main()
{
    int i,j,n,m,p;
    cout<<"n= "; cin>>n;
    cout<<"m= "; cin>>m;
    int** a=new int* [n]; 
    for(i=0;i<n;i++) a[i]=new int [m]; 
    cout<<"Matrix"<<endl;
    for(i=0;i<n;i++)
    {
        for(j=0;j<m;j++)
        {
            a[i][j]=rand()%20;
            cout<<"  "<<a[i][j];  
        }
        cout<<endl;
    }
    for(i=0;i<n;i++)
    { 
        int p=1;
        for(j=0;j<m;j++) p*=a[j][i];
        cout<<p<<endl;
    }
    for(i=0;i<n;i++) delete [] a[i];
    delete [] a; 
    system("pause");
    return 0;
}



1



2 / 2 / 1

Регистрация: 26.10.2010

Сообщений: 67

22.05.2011, 17:26

 [ТС]

3

-comrade-, да) спасибо большое



0



Product of array elements

Syntax

Description

example

B = prod(A)
returns the product of the array elements of A.

  • If A is a vector, then
    prod(A) returns the product of the
    elements.

  • If A is a nonempty matrix, then
    prod(A) treats the columns of
    A as vectors and returns a row vector of the
    products of each column.

  • If A is an empty 0-by-0 matrix,
    prod(A) returns 1.

  • If A is a multidimensional array, then
    prod(A) acts along the first
    nonsingleton dimension and returns an array of products.
    The size of B in this dimension reduces to
    1, while the sizes of all other dimensions
    remain the same as in A.

  • If A is a
    table or timetable, then prod(A) returns a
    one-row table of the products of each variable. (since R2023a)

prod computes and returns B as
single when the input, A, is
single. For all other numeric and logical data types,
prod computes and returns B as
double.

example

B = prod(A,"all")
returns the product of all elements of A.

example

B = prod(A,dim)
returns the product along dimension dim. For example, if
A is a matrix, prod(A,2) is a column
vector containing the products of each row.

example

B = prod(A,vecdim)
returns the product based on the dimensions specified in the vector
vecdim. For example, if A is a matrix,
then prod(A,[1 2]) returns the product of all elements in
A because every element of a matrix is contained in the
array slice defined by dimensions 1 and 2.

example

B = prod(___,outtype)
returns an array in the class specified by outtype, using any
of the input arguments in the previous syntaxes. outtype can
be "double", "native", or
"default".

example

B = prod(___,nanflag)
specifies whether to include or omit NaN values in
A. For example, prod(A,"omitnan")
ignores NaN values when computing the product. By default,
prod includes NaN values.

Examples

collapse all

Product of Elements in Each Column

Create a 3-by-3 array whose elements correspond to their linear indices.

A = 3×3

     1     4     7
     2     5     8
     3     6     9

Find the product of the elements in each column. The length of the first dimension is 1, and the length of the second dimension matches size(A,2).

Product of Logical Input

Create an array of logical values.

A = [true false; true true]
A = 2x2 logical array

   1   0
   1   1

Find the product of the elements in each column.

The output has type double.

Product of Elements in Each Row

Create a 3-by-3 array whose elements correspond to their linear indices.

A = 3×3

     1     4     7
     2     5     8
     3     6     9

Find the product of the elements in each row and reduce the length of the second dimension to 1. The length of the first dimension matches size(A,1), and the length of the second dimension is 1.

Product of Array Page

Create a 3-D array and compute the product over each page of data (rows and columns).

A(:,:,1) = [2 4; -2 1];
A(:,:,2) = [1 2; -5 3];
A(:,:,3) = [4 4; 1 -3];
B1 = prod(A,[1 2])
B1 = 
B1(:,:,1) =

   -16


B1(:,:,2) =

   -30


B1(:,:,3) =

   -48

To compute the product over all dimensions of an array, you can either specify each dimension in the vector dimension argument, or use the "all" option.

Single-Precision Input Treated as Double

Create a 3-by-3 array of single-precision values.

A = single([1200 1500 1800; 1300 1600 1900; 1400 1700 2000])
A = 3x3 single matrix

        1200        1500        1800
        1300        1600        1900
        1400        1700        2000

Find the product of the elements in each row by multiplying in double precision.

B = 3×1
109 ×

    3.2400
    3.9520
    4.7600

The output is double precision.

Integer Data Type for Input and Output

Create a 3-by-3 array of 8-bit unsigned integers.

A = uint8([1:3:7;2:3:8;3:3:9])
A = 3x3 uint8 matrix

   1   4   7
   2   5   8
   3   6   9

Find the product of the elements in each column natively in uint8.

B = 1x3 uint8 row vector

     6   120   255

The result is an array of 8-bit unsigned integers.

Product Excluding Missing Values

Create a matrix containing NaN values.

A = [1.77 -0.005 NaN -2.95; NaN 0.34 NaN 0.19]
A = 2×4

    1.7700   -0.0050       NaN   -2.9500
       NaN    0.3400       NaN    0.1900

Compute the products of the matrix, excluding NaN values. For matrix column that contain any NaN value, prod computes with the non-NaN elements. For matrix columns that contain all NaN values, the product is 1.

B = 1×4

    1.7700   -0.0017    1.0000   -0.5605

Input Arguments

collapse all

AInput array
vector | matrix | multidimensional array | table | timetable

Input array, specified as a vector, matrix, multidimensional array, table, or
timetable.

Data Types: double | single | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | logical | table | timetable
Complex Number Support: Yes

dimDimension to operate along
positive integer scalar

Dimension
to operate along, specified as a positive integer scalar. If you do not specify the dimension,
then the default is the first array dimension of size greater than 1.

Dimension dim indicates the dimension whose
length reduces to 1. The size(B,dim) is 1,
while the sizes of all other dimensions remain the same.

Consider a two-dimensional input array, A.

  • If dim = 1, then prod(A,1) returns
    a row vector containing the product of the elements in each column.

    prod(A,1) column-wise computation.

  • If dim = 2, then prod(A,2) returns
    a column vector containing the product of the elements in each row.

    prod(A,2) row-wise computation.

prod returns A when dim is
greater than ndims(A).

Data Types: double | single | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

vecdimVector of dimensions
vector of positive integers

Vector of dimensions, specified as a vector of positive integers. Each
element represents a dimension of the input array. The lengths of the output
in the specified operating dimensions are 1, while the others remain the
same.

Consider a 2-by-3-by-3 input array, A. Then
prod(A,[1 2]) returns a 1-by-1-by-3 array whose
elements are the products of each page of A.

prod(A,[1 2]) collapses the pages of a 2-by-3-by-3 array into a 1-by-1-by-3 array.

Data Types: double | single | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

outtypeOutput class
"default" (default) | "double" | "native"

Output class, specified as "default",
"double", or "native", and which
defines the data type of the output, B.

outtype Output data type
"default" double, unless the input data type is
single, table, or
timetable. In which case, the output
data type is single or
table, respectively.
"double" double, unless the input data type is
table or
timetable. In which case, the output data
type is table.
"native" Same data type as the input array, A,
unless the input data type is timetable.
In which case, the output data type is
table.

nanflagMissing value condition
"includemissing" (default) | "includenan" | "omitmissing" | "omitnan"

Missing value condition, specified as one of these values:

  • "includemissing" or
    "includenan" — Include
    NaN values in A when
    computing the product. If any element in the operating dimension is
    NaN, then the corresponding element in
    B is NaN.
    "includemissing" and
    "includenan" have the same behavior.

  • "omitmissing" or "omitnan"
    — Ignore NaN values in
    A, and compute the product over fewer points.
    If all elements in the operating dimension are
    NaN, then the corresponding element in
    B is 1. "omitmissing" and
    "omitnan" have the same behavior.

Output Arguments

collapse all

B — Product array
scalar | vector | matrix | multidimensional array | table

Product array, returned as a scalar, vector, matrix, multidimensional array, or table.

The class of B is as follows:

  • If the outtype argument specifies "default" or is not
    used

    • and the input is not single,
      table, or
      timetable, then the output is
      double.

    • and the input is single, then
      the output is single.

    • and the input is table or
      timetable, then the output is
      table.

  • If the outtype argument specifies
    "double", then the output is
    double regardless of the input data type,
    unless the input is table or
    timetable.

  • If the outtype argument specifies
    "native", then the output is the same
    data type as the input, unless the input is
    timetable. In which case, the output is
    table.

More About

collapse all

First Nonsingleton Dimension

The first nonsingleton
dimension is the first dimension of an array whose size is not equal
to 1.

For example:

  • If X is a 1-by-n row vector, then
    the second dimension is the first nonsingleton dimension of X.

  • If X is a 1-by-0-by-n empty array,
    then the second dimension is the first nonsingleton dimension of X.

  • If X is a 1-by-1-by-3 array, then
    the third dimension is the first nonsingleton dimension of X.

Extended Capabilities

Tall Arrays
Calculate with arrays that have more rows than fit in memory.

This function fully supports tall arrays. For
more information, see Tall Arrays.

C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.

Usage notes and limitations:

  • If you supply dim, it must be a
    constant.

  • See Variable-Sizing Restrictions for Code Generation of Toolbox Functions (MATLAB Coder).

GPU Code Generation
Generate CUDA® code for NVIDIA® GPUs using GPU Coder™.

Usage notes and limitations:

  • If you supply dim, it must be a constant.

Thread-Based Environment
Run code in the background using MATLAB® backgroundPool or accelerate code with Parallel Computing Toolbox™ ThreadPool.

This function fully supports thread-based environments. For
more information, see Run MATLAB Functions in Thread-Based Environment.

GPU Arrays
Accelerate code by running on a graphics processing unit (GPU) using Parallel Computing Toolbox™.

Usage notes and limitations:

  • 64-bit integers are not supported with the "native"
    option.

  • The order of the products in prod operation is not
    defined. Therefore, the prod operation on a GPU array
    might not return exactly the same answer as the prod
    operation on the corresponding numeric array.

For more information, see Run MATLAB Functions on a GPU (Parallel Computing Toolbox).

Distributed Arrays
Partition large arrays across the combined memory of your cluster using Parallel Computing Toolbox™.

Usage notes and limitations:

  • The order of the products in prod operation is not
    defined. Therefore, the prod operation on a distributed
    array might not return exactly the same answer as the
    prod operation on the corresponding numeric array.
    The difference might be significant when A is a signed
    integer type and its product is accumulated natively.

For more information, see Run MATLAB Functions with Distributed Arrays (Parallel Computing Toolbox).

Version History

Introduced before R2006a

expand all

R2023a: Specify missing value condition

Include or omit missing values in the input array when computing the product by
using the "includemissing" or "omitmissing"
options. These options have the same behavior as the "includenan"
and "omitnan" options, respectively.

R2023a: Perform calculations directly on tables and timetables

The prod function can calculate on all variables within a table or
timetable without indexing to access those variables. All variables must have data types
that support the calculation. For more information, see Direct Calculations on Tables and Timetables.

R2018b: Operate on multiple dimensions

Operate on multiple dimensions of the input array at a time. Specify a vector of
operating dimensions, or specify the "all" option to operate on
all array dimensions.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace ConsoleApplication9
{
    class Program
    {
        static void Main(string[] args)
        {
            uint M, N;
            Random rnd = new Random();
            Console.WriteLine("Введите M");
            M = uint.Parse(Console.ReadLine());
            Console.WriteLine("Введите N");
            N = uint.Parse(Console.ReadLine());
            int[,] Matrica = new int[M, N];
 
            int[] proizved = new int[M];
            Console.WriteLine("Заполняем матрицу случайными числами");
                for (int i = 0; i < M; i++)
                {
                    for (int j = 0; j < N; j++)
                    {
                        Matrica[i, j] = rnd.Next(2,10);
                    }
                }

                for (int i = 0; i < proizved.Length; i++)
                {
                    proizved[i] = 1;
                }
 
                uint tmp = N;
                for (int i = 0; i < M; i++)
                {
                    tmp--;
                    for (int j = 0; j < N; j++)
                    {
                        Console.Write(Matrica[i, j] + " ");
                         
                    }
                    Console.WriteLine();
                }
 
                for (int i = 0; i < N; i++)
                {
                    
                    for (int j = 0; j < M; j++)
                    {
                        
                            proizved[i] *= Matrica[j, i];
                    }
                    Console.WriteLine();
                }

                Console.WriteLine("Произведение элементов каждого столбца: t ");
                for (int i = 0; i <proizved.Length; i++)
                {
                    Console.WriteLine("tt" + proizved[i].ToString());
                    Console.WriteLine();
                }
 
        }
    }
}

#include <iostream>
#include <windows.h>
#include <ctime>
#include <algorithm>
#include <iomanip>

using namespace std;

int main()
{
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
srand(time(NULL));
system(“color 0A”);

cout << “Введите размеры матрицы “;
size_t n, m;
cin >> n >> m;
auto **a = new int*[n];
for (size_t count = 0u; count < n; ++count)
a[count] = new int[m];

auto get_num = []()
{
auto value = rand() % 5;
cout << setw(5u) << value;
return value;
};
auto get_string = [a, n, m, get_num]()
{
auto str = new int[m];
generate(str, str + m, get_num);
cout << endl;
return str;
};
cout << “Исходная матрица: ” << endl;
generate(a, a + n, get_string);
cout << “Поизведения для столбиков” << endl;
for (size_t u = 0u; u < m; ++u)
{
long long pp = 1;
for (size_t p = 0u; p < n; ++p)
{
pp *= a[p][u] ? a[p][u] : 1;
}
cout << setw(5u) << pp;
}
cout << endl;

system(“pause”);
return 0;
}

Matrix20. Дана матрица размера $$M times N$$. Для каждого столбца матрицы найти произведение его элементов.

Решение:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

program Matrix20;

var

  a:array [1..10,1..10] of integer;

  Mult,M, N, i, j:Integer;

begin

Write(‘N: ‘);

Readln(N);

Write(‘M: ‘);

Readln(M);

for  i:=1 to M do

  begin

   writeln(i,‘: ‘);

   for j:=1 to N do

    begin

     Write(j,‘ : ‘);

     Read(a[i,j]);

    end;

  end;

  For j:=1 to N do

   begin

    Mult:=1;

    for i:=1 to M do Mult:=Mult*a[i,j];

    Writeln(j,‘ Proizvedenie:’,Mult);

   end;

end.

Другие задачи из раздела Matrix можно посмотреть здесь.

Добавить комментарий