0

I want to create a vector containing strings in loop.

After creating the code my output should be a row matrix having 30 elements in a loop starting from 'Mon' ending on 'Tue'

My vector should contain these seven elements in a continuous loop 'Mon' , 'Tue' ,'Wed' , 'Thu' , 'Fri' , 'Sat' , 'Sun'

Please give me some idea

I would be bad in English as it's a second language for me so please try to bear grammatical errors.

0

1 Answer 1

4

You can't have these strings in a vector because each element in a vector is a single integral type, so a double, integer, character, etc. What you want is a set of characters per entry, and if you want that it's best to use a cell array.

You can first create a cell array of strings that contain Mon to Sun, then just index into it with a modulo operator:

>> A = {'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'};
>> B = A(mod(0:29, numel(A)) + 1)

B = 

  Columns 1 through 9

    'Mon'    'Tue'    'Wed'    'Thu'    'Fri'    'Sat'    'Sun'    'Mon'    'Tue'

  Columns 10 through 18

    'Wed'    'Thu'    'Fri'    'Sat'    'Sun'    'Mon'    'Tue'    'Wed'    'Thu'

  Columns 19 through 27

    'Fri'    'Sat'    'Sun'    'Mon'    'Tue'    'Wed'    'Thu'    'Fri'    'Sat'

  Columns 28 through 30

    'Sun'    'Mon'    'Tue'

I wouldn't use a loop here, but if you insist on using a loop, you can iterate over from 1 to 30 and use the same principle:

A = {'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'};
B = cell(1,30); %// Initialize empty cell array
for idx = 1 : 30 %// Going from 1 up to 30...
    index = mod(idx-1, numel(A)) + 1; %// Determine the right place to index into A
    B(idx) = A(index); %// Get corresponding day and place into output
end

You'll get the same answer as above.

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

3 Comments

Wow! using mod here is clever!
@SanthanSalai - hehe thanks :) It just comes from experience. Usually when you populate elements in an array where elements repeat themselves or cycle back to the beginning from a smaller source array, mod is the way to go.
@AmmarNasser Note that pointers (c like languages) or references (eg. c++ or java) are not supported in matlab. Some types like Matlab cells use this built in, but, the developer cannot use pointers or references. Since a string is normally represented as an array of characters, this means that a vector of "strings" is really a vector of pointers, or references. This means that in a Matlab vector you can only have char. To have "strings", you need a type like cell, which store elements by its reference.

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.