J.Smith
J.Smith

Reputation: 335

Get numbers in a matrix in different set positions

I have a matrix 1x5000 with numbers. Now I am interested in getting values from the matrix in different positions, more precisely in six different places of the matrix. The places should be based on the length, these are the numbers I want to get out:

  1. Number in 1/6 of the matrix length
  2. Number in 2/6 of the matrix length
  3. Number in 3/6 of the matrix length
  4. Number in 4/6 of the matrix length
  5. Number in 5/6 of the matrix length
  6. Number in 6/6 of the matrix length

These values could be printed out in another matrix, so assume the matrix is 1x5000, 3/6 would give the number in the middle of the matrix. I am new in Matlab and therefore the help is much appreciated!

Upvotes: 1

Views: 62

Answers (2)

Mikhail_Sam
Mikhail_Sam

Reputation: 11238

Since your question is unclear I can try to give you an example. First of all you can use numel function to get matrix's size.

It's easy to get necessary element in Matlab: you can address directly to any element if you know its number (index). So: x(100) returns 100th element. Now you got size and know what to do. Last moment - what to do if numel(x) / 6 return non integer?

You can use rounding functions: ceil, floor or round.

index = ceil(numel(x)/6) %if you want NEXT element always
result = x(index)

Next step: there are a lot of ways to divide data. For example now you have just 6 numbers (1/6, 2/6 and so on) but what if there are 1000 of them? You can't do it manually. So you can use for loop, or you can use matrix of indexes or perfect comment Stewie Griffin.

My example:

divider = [6 5 4 3 2 1] % lets take 1/6 1/5 1/4 1/3 1/2 and 1/1
ind = ceil( numel(x)./divider)
res = x(ind)

Upvotes: 1

Ibrahim Ali Khan
Ibrahim Ali Khan

Reputation: 92

The colon notation in MATLAB provides an easy way to extract a range of elements from v:

v(3:7)    %Extract the third through the seventh elements

You could either manually input range or use a function to convert fractions into suitable ranges

Upvotes: 0

Related Questions