Fatimah
Fatimah

Reputation: 169

The idea of C array in matlab

Is it possible to apply the idea of array in C to MATLAB For example, if we have Double array[10]; and if we want to assign a value we write for example Array[5]=2;

Is there any way to write equivalent one in MATLAB ?

Upvotes: 0

Views: 338

Answers (4)

Nzbuu
Nzbuu

Reputation: 5251

There is no indexing operator []. You must use () for indexing array.

If you write

x = 1:10;
x[2]

then you'll get the following error

 x[2]
 |
Error: Unbalanced or unexpected parenthesis or bracket.

Upvotes: 0

Krishna
Krishna

Reputation: 1

Yes you can. Arrays are used in C and MATLAB and they can be used for the same functions. Except, please keep in mind the array-indexing of C and MATLAB are different.

The first element of a C array has an index of zero. i.e. in X = [10 20 30 40], x[0] will return 10. But in MATLAB, this will give an error. To access the number 10, you have to use the expression x[1] in MATLAB.

Upvotes: 0

Andrey Rubshtein
Andrey Rubshtein

Reputation: 20915

You can define your own class, override the [] operator.
I described the mechanism in Here
Since it is a custom function, you might as well change the 1-based indexing to 0-based indexing.

Regarding the constructor, I doubt that you can do it.

Anyhow, why would you want to do it?
You will confuse all of the Matlab users, and cause havoc.
When in Rome, do as Romans do.

Upvotes: 2

Chris
Chris

Reputation: 46316

I'm not sure what you mean by "Is it possible to apply the idea of array in C to MATLAB". An array is just a 1D list of numbers (or other data types). MATLAB primarily is designed to work with matrices (MATLAB is short for Matrix laborartory) and an array or vector is simply a special case of a matrix. So I guess the answer to your question is yes, if I have understood correctly.

To initialise arrays or matrices in MATLAB we use zeros or ones:

>> array = zeros(1,5)

array =

     0     0     0     0     0

We can then index elements of the array in the same way as C:

>> array(3) = 3

array =

     0     0     3     0     0

Note, however, that MATLAB array indexing is one based whereas C arrays are zero based.

This article describes matrix/array indexing in MATLAB.

Upvotes: 2

Related Questions