MATLAB Answers

How to manipulate array?

3 views (last 30 days)
Alessandro Musso Iudica
Alessandro Musso Iudica on 22 Jan 2020
Answered: Steven Lord on 22 Jan 2020
Hi, I'm just approaching with matlab programming. My problem is how to manipulate arrays that result from a function.
As example consider:
matrix = [1 2 3, 4 5 6, 7 8 9]
[number_rows, number_columns] = size (matrix)
If I wanted to use number_columns in some calculation i have to write the code 2 times:
[number_rows, number_columns] = size (matrix)
my_columns = number_columns
How can I use the second element of the array immediately?
I'm sure it is easy

  0 Comments

Sign in to comment.

Answers (2)

Adam
Adam on 22 Jan 2020
Edited: Adam on 22 Jan 2020
Just use it! Where you are going to use my_columns, just use number_columns, e.g.
newMatrix = zeros( number_rows, number_columns );
Note though that in your example:
matrix = [1 2 3, 4 5 6, 7 8 9]
just produces a matrix with a single row and 9 columns. The , in there are no different to spaces. Using ; would give a 3-by-3 matrix is that is what you expect.

  0 Comments

Sign in to comment.


Steven Lord
Steven Lord on 22 Jan 2020
For the specific example of the size function, if you want to know the number of columns in the input array, tell size that you want the size of the input array in the second dimension.
A = ones(3, 4);
numColumns = size(A, 2)
You don't have to assign it to a variable, you can use it inside another function call like this.
disp("A has " + size(A, 2) + " columns.")
Note that there can be a difference between size with a dimension and size without.
B = ones(3, 4, 5);
[numRows, numColumnsTimesNumPages] = size(B)
numColumns = size(B, 2)
See the description of the sz1, ... szN output arguments on the size documentation page for an explanation.

  0 Comments

Sign in to comment.

Tags

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!