Vignesh R
Vignesh R

Reputation: 53

changing the index value of vector in matlab

How do I change the index values of a vector/array in MATLAB?
For example, A = [1 2 3 4 5]. Here A(1) = 1, A(2) = 2 and so on. I want to change the base value of the index to say 1001 or 2001 so that now A(1001) = 1 or A(2001) = 1.

Can someone please tell me how it can be done in MATLAB. Appreciate the help. Thanks in advance.

Upvotes: 1

Views: 564

Answers (2)

Hoki
Hoki

Reputation: 11792

You cannot directly change the indexing of the arrays in Matlab, but you can use a helper anonymous function to convert your study ID to the proper index.

A = [1 2 3 4 5] ;
sid = @(ix) ix-1000 ;

Now sid (short for studyID but you can name it what you like) will always remove 1000 to whatever index you throw at it. It works for a single index:

>> A(sid(1002))
ans =
     2

But also for multiple indices:

>> A(sid([1001 1003:1004]))
ans =
     1     3     4

Upvotes: 2

Dan
Dan

Reputation: 45741

I don't think you can do that really but you could 'spoof' it using a sparse matrix perhaps (depending strongly on what your application is):

b(1001:1005) = sparse(A)

However for what you've mentioned in your comments it makes much more sense to do something like this:

study = 1001:1005;
results = 1:5;  %// This is your A

ind = A == 3;

%// Now find the study number that matches your specific result:
study(ind)

Upvotes: 3

Related Questions