MATLAB Answers

How to manipulate array?

조회 수: 6(최근 30일)
Alessandro Musso Iudica
답변: Steven Lord 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

댓글을 달려면 로그인하십시오.

답변(2개)

Adam
Adam 22 Jan 2020
편집: Adam 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

댓글을 달려면 로그인하십시오.


Steven Lord
Steven Lord 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

댓글을 달려면 로그인하십시오.

태그

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by