1

For some reason when I try the size function in matlab, I cannot determine the datatype and cannot use it the way I want.

data = [[3,4,56,1,2],[3,1,3,45,2]];

Then, I want to get the second dimension:

size(data)(2)

throws an error:

>> size(data)(2)
Error: ()-indexing must appear last in an index expression.

Then I try this:

>> n = size(data)

n =

     1    10

>> n(2)

ans =

    10

And it is no problem. Blows my mind. why? and, what type of data type does size return?

1
  • Interestingly, octave has no problem with size(data)(2). Commented Jun 6, 2015 at 22:11

2 Answers 2

2

Try size(data,2). This is pretty basic.

Sign up to request clarification or add additional context in comments.

Comments

1

That is not allowed in MATLAB, as your error says. To use the size function on a multi-dimensional array (matrix), use size(data, 1) to get the number of rows and size(data, 2) to get the number of columns.

Here is the (first bit of the) result from help size on MATLAB.

>>help size
'size' is a built-in function from the file libinterp/corefcn/data.cc

 -- Built-in Function: size (A)
 -- Built-in Function: size (A, DIM)

 Return the number of rows and columns of A.

 With one input argument and one output argument, the result is
 returned in a row vector.  If there are multiple output arguments,
 the number of rows is assigned to the first, and the number of
 columns to the second, etc.

Similarly, if you have a matrix A = [1, 2, 3; 4, 5, 6], use the same method to access the elements. For example, A(1,1) = 1 (NOT A(1)(1)), and A(2,2) = 5.

Cheers!

EDIT: Also, did you mean data = [[3,4,56,1,2];[3,1,3,45,2]]; (notice the semi-color separating the rows)? Because data = [[3,4,56,1,2],[3,1,3,45,2]]; would return a long 10-dimensional vector instead of a 5x2 matrix.

3 Comments

I think you meant "NOT A(1)(1)"? :)
@jadhachem: Yep! That's what I mean, fixed it btw.
Thanks for the responses, guys. However, as I said in my question, it isn't clear to me why it works to index like (1,1), but it doesn't work to index in two separate operations, like shown in my question. Is there a good explanation?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.