How does reshape function work? and also how to use sum(A,dim) in the code?
8 views (last 30 days)
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)?
More Answers (2)
Awais Saeed on 22 Aug 2021
% 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 on 22 Aug 2021
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])
z = reshape(x, [2 4 2])
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.