-3

I have this question to which I have a partial answer to. Hope you would help me in doing the rest:

  • Part A: Create a vector of random numbers of size 1×20, and name it as data. The values of these random numbers should be in the range between 0 and 1.
    Answer: data=rand(1,20);
  • Part B: Create a 1×10 vector and name it as half_data which consists of values from the first half of the vector data
  • Part C:Create a 1×10 vector even_data which is composed of even-index elements of data.

Help me out do (part B) and (part C)

Kijewski
  • 25,517
  • 12
  • 101
  • 143
UMJ
  • 3
  • 1
  • 4

1 Answers1

0
data = [1:10];
#% Part B
half_data = data(1:end/2);
#% Part C
even-index = data(2:2:end);

The syntax is: vector(first_index : step_size : last_index) (spaces optional)

See further: http://en.wikibooks.org/wiki/Octave_Programming_Tutorial/Vectors_and_matrices#Ranges

Kijewski
  • 25,517
  • 12
  • 101
  • 143
  • Thanks alot KAY! You are GOD for me as far as MATLAB is concerned ! :) Could you help me know how do we create an EMPTY vector size 1X10? – UMJ Sep 18 '14 at 03:37
  • @UjjwalMalik as far as I know there is no real empty vector in matlab. You could either use cell-datatype with `x=cell(1,10);` or if you want double you could use: `x=zeros(1,10)` in that case it would be preallocated with zeros. Obviously you could change that to `NaN` but its not possible to leave them empty if you use double-datatype. If you want to preallocate a variable you can also just use: `x=[]` (but this wouldnt have the size 1x10) – The Minion Sep 18 '14 at 07:15
  • @TheMinion What about `sparse`? – sobek Sep 18 '14 at 07:38
  • @sobek how would you do that? If I understand and use `sparse` right it squeezes out all zero elements. Yet you wouldnt be able to have an empty 1x10 vector with it... or are you refering to my point that you cant leave them empty? If so I think i read somewhere that sparse is only changing the type of allocation to take up less space (yet it actually still saves the position of the zeros) otherwise you wouldnt be able to differentiate between [0 1;2 3] and [2 1; 0 3] right? – The Minion Sep 18 '14 at 07:50
  • @TheMinion I guess it depends on one's definition of "empty". As far as i am aware, sparse is going to be the closest you are going to get to storing "nothing" in an element while retaining the dimension of its container. Returning to the question, why does the vector need to be empty? To indicate that no valid value has been written to it? In that case, use NaN as mentioned by The Minion or use another value that is not inside the range of valid values (if applicable, e.g. -1 if valid range is positive numbers) – sobek Sep 18 '14 at 08:03