MATLAB Answers

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

1 view (last 30 days)
S Priya on 22 Aug 2021
Commented: Awais Saeed on 23 Aug 2021
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)?
##### 0 CommentsShowHide -1 older comments

Sign in to comment.

### Accepted Answer

Matt J on 22 Aug 2021
Edited: Matt J on 22 Aug 2021
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...
##### 1 CommentShowHide None
S Priya on 23 Aug 2021
Thank you.

Sign in to comment.

### More Answers (2)

Awais Saeed on 22 Aug 2021
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
##### 2 CommentsShowHide 1 older comment
Awais Saeed on 23 Aug 2021
you are welcome

Sign in to comment.

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])
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.
##### 1 CommentShowHide None
S Priya on 23 Aug 2021
Thank you.

Sign in to comment.

### Community Treasure Hunt

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

Start Hunting!