How to manipulate array?

2 次查看(过去 30 天)
Alessandro Musso Iudica
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

回答(2 个)

Adam
Adam 2020-1-22
编辑:Adam 2020-1-22
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.

Steven Lord
Steven Lord 2020-1-22
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.

类别

Help CenterFile Exchange 中查找有关 Data Type Identification 的更多信息

标签

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by