两个矩阵相乘是怎么算的(详见问题补充)

两个矩阵相乘是怎么算的(详见问题补充),第1张

如果矩阵a与矩阵b相乘必须:
a中的列数必须b中行数。
如果不相同,则ab无意义;
注意:
不要求a的行数与b的列数是否相等。
ab中的第i行j
列的元素要等于a中的i
行元素与b中的j列元素对应元素相乘再相加。
(即a中i行的第一个元素与b中j列的第一个元素相乘再加上i行的第二个元素与b中j列的第二个元素相乘,一直加到a中i行的最后一个元素与b中j列的最后一个元素相乘)

应该是你要的吧。
计算两个矩阵乘积。(附本题原题)
/计算两个矩阵的乘积
hold
by
cljnnn-hit
date
2006-12-2
13/
#include
<stdioh>
#include
<stdlibh>
void
calculate
(int
line_1,
int
column_line,
int
columns_2,
int
ptr_memory);/计算并输出结果/
int
main()
{
int
ptr_memory;
/申请内存用,存储此内存的首地址/
int
times,
line_1,
column_line,
columns_2;/分别存储计算次数,第一个矩阵的行数,列数(第二个矩阵的行数),第二个矩阵的列数/
int
i,
j;
scanf("%d",&
times);/输入计算次数/
for
(i
=
1;
i
<=
times;
i++)/计算times次/
{
scanf("%d%d%d",
&line_1,
&column_line,
&columns_2);/输入要计算的两个矩阵的规格/
ptr_memory
=
(int
)
malloc((line_1

column_line
+
column_line

columns_2)

sizeof(int));/申请适当的内存/
if
(ptr_memory)
/申请到就进行计算/
{
for
(j
=
0;
j
<
line_1

column_line
+
column_line

columns_2;
j++)
scanf("%d",
ptr_memory
+
j);
/输入这两个矩阵/
calculate
(line_1,
column_line,
columns_2,
ptr_memory);/计算并输出结果/
}
else/未申请到打印/
printf("Not
Enough
Memory!\n");
free(ptr_memory);/释放申请的内存/
}
return
0;
}
/功能:计算并输出结果
参数:第一个矩阵的行数,列数(第二个矩阵的行数),第二个矩阵的列数,申请的内存的首地址
返回:无/
void
calculate
(int
line_1,
int
column_line,
int
columns_2,
int
ptr_memory)
{
int
i,
j,
k;
int
mid_result1,
mid_result2,
result;/分别存储中间计算数据1,2,计算结果/
for
(
i
=
0;
i
<
line_1;
i++)
{
for
(j
=
0;
j
<
line_1;
j++)
{
result
=
0;/将结果初始化/
for
(k
=
0;
k
<
column_line;
k++)
{
mid_result1
=
column_line

i
+
k;/第一个乘数相对位置/
mid_result2
=
line_1

column_line
+
columns_2

k
+
j;/第二个乘数相对位置/
result
+=
(ptr_memory
+
mid_result1)

(ptr_memory
+
mid_result2);
/累计计算公式/
}
if
(j
==
columns_2
-
1)/如果到了换行的时候换行/
printf("%d\n",result);
else
printf("%d
",result);/其他情况不换行/
}
}
}
本题原题:
Input
The
first
line
of
input
is
the
number
of
all
the
test
cases
that
follow
For
each
test
case,
there
are
three
positive
integer
m,
n,
p
(m,
n,
p
<=
100)
on
the
first
line,
meaning
that
A's
dimension
is
m
rows
by
n
columns
while
B's
is
n
rows
by
p
columns
Then
comes
the
data
of
matrices
A
and
B
Matrix
A
is
represented
by
m
lines
of
integers
ranging
in
[-1000,
1000],
with
each
line
containing
n
integers
separated
by
a
space
A
line
is
corresponding
to
a
row
of
a
matrix
The
data
format
for
matrix
B
is
much
the
same
except
for
its
potentially
different
dimensions
Please
refer
to
the
section
Sample
Input
Output
For
each
test
case,
print
the
product
of
A
multiplied
by
B
in
the
form
described
in
the
section
Input,
but
do
not
include
any
dimension
description
Sample
Input
2
2
2
2
1
2
3
4
1
2
3
4
1
2
1
1
0
0
1
Sample
Output
7
10
15
22
0

矩阵的分块多用于稀疏矩阵,把其中的零元素分块独立出来,以简化运算。
(零矩阵与任意矩阵的乘积都是零矩阵,因此只需要计算非零矩阵之间的乘积)
矩阵分块的唯一要求是前一个矩阵的列分割与后一个矩阵的行分割一致。
例如:计算AB,A从左至右划分为3列+5列+2列,则B必须从上至下划分为3行+5行+2行。
(A的行分割和B的列分割不限)


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/13159884.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-06-13
下一篇 2023-06-13

发表评论

登录后才能评论

评论列表(0条)

保存