How does reshape function work? and also how to use sum(A,dim) in the code?

8 次查看(过去 30 天)
1.I want to understand how reshape fuction actually works?
2. While using the sum(A,dim) what the actual meaning of dim here?For example
if A=[16 5 9 4;3 10 6 15;2 11 7 14]
and if we want sum, then why it represented as sum(A,2) and not sum(A,3)?

采纳的回答

Matt J
Matt J 2021-8-22
编辑:Matt J 2021-8-22
Simplest way to understand reshape is through examples
A=1:12
A = 1×12
1 2 3 4 5 6 7 8 9 10 11 12
reshape(A,3,4)
ans = 3×4
1 4 7 10 2 5 8 11 3 6 9 12
As for sum(A,dim), the sum will be along columns when dim=1, along rows if dim=2, along the 3rd dimension if dim=3 and so forth...

更多回答(2 个)

Awais Saeed
Awais Saeed 2021-8-22
clc;clear;close all
% In reshape, the first parameter is the matrix you want to reshape
% Second parameter is number of rows
% Third is number of columns
% if you do not know the number of rows or columns, put [] and the
% command will automatically find the number
% Example of reshape:
% Convert A into a sigle column (if you do not know the number of rows)
A = 1:16
A1 = reshape(A, [], 1);
% Convert A into a sigle column (if you know the number of rows)
A2 = reshape(A, 16, 1);
% Example of sum
B = [1:5; 6:10 ; 11:15]
sum(B,2) % 2 means to sum the elements of rows
sum(B,1) % 1 means to sum the elements of columns
Run this script to see what each steps does

Steven Lord
Steven Lord 2021-8-22
For reshape, conceptually you can think of it as taking a long string of elements:
x = 1:16;
and putting them into the elements of an array of the size to which you're reshaping, first going down the columns then across the rows and on to filling in pages.
y = reshape(x, [4 4])
y = 4×4
1 5 9 13 2 6 10 14 3 7 11 15 4 8 12 16
z = reshape(x, [2 4 2])
z =
z(:,:,1) = 1 3 5 7 2 4 6 8 z(:,:,2) = 9 11 13 15 10 12 14 16
The picture in the description of the dim input argument on the documentation page for the sum function may help you understand how that function interprets the dimension input.

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by