g_kfupm
g_kfupm

Reputation: 11

How can we assign letters to numbers

I have the following:

d=[1 2 3 4 5 6 7]

I want Matlab to assign a day name to every number by doing a loop or

any suitable method as follows:

1 =tuesday

2=wednesday

.

.

.

7=monday

the results I am aiming to get after running the program is :

the Matlab window asks the user to enter a number from 1 to 7

n=('enter a number from 1 to 7')

then,

if we enter ,for example, 4 , this means that the printed result is: Friday

or

if we entered , for example , 7, this means that the printed result is: Monday

and so on

Is there any way to do this

regards

Upvotes: 0

Views: 3736

Answers (2)

zellus
zellus

Reputation: 9592

Using a map might be one approach:

weekDays = containers.Map({1, 2, 3, 4, 5, 6, 7} , ...
{'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'});

number = input('enter a number from 1 to 7');
disp(sprintf('You did choose %s\n', weekDays(number)));


EDIT: Using the solution by Bill Cheatham you end up with

weekdays = {'Mon', 'Tues', 'Weds', 'Thurs', 'Fri', 'Sat', 'Sun'};
number = input('enter a number from 1 to 7');
disp(sprintf('You did choose %s\n', weekdays{number}));

Upvotes: 1

Bill Cheatham
Bill Cheatham

Reputation: 11937

You could use a cell array, which allows you to store an array of text strings. The curly bracket is the key:

>> weekdays = {'Mon', 'Tues', 'Weds', 'Thurs', 'Fri', 'Sat', 'Sun'};
>> weekdays{4}

ans =

Thurs

Edit: You can get the relevant number from the user by using MATLAB's input function:

n = input('Enter your number:');
disp(weekdays{n})

Upvotes: 5

Related Questions