user input and save the the file name

6 views (last 30 days)
azie
azie on 16 Jul 2015
Commented: Star Strider on 16 Jul 2015
Hi, need help on the programming. I want to input an alphabet, then the program will give a value according to the alphabet that I have input. Next the alphabet should be the filename(.mat) and appear as the chosen alphabet in workspace. Below is my code. Its run well until x value calculation. but i don't know what is the next step. Please help.
%%myprogram
alpha=input('input:\n','s');
if 'A'
i=1;
elseif 'B'
i=4;
else
i=8;
end
x=[i+2 i];
filename = alpha;
save(filename, 'x');
Example: if user input is 'B', the final output should be file B.mat with value B=[6 4]

Answers (1)

Star Strider
Star Strider on 16 Jul 2015
There are two important problems with your code.
First, if you want to compare strings, such as ‘alpha’ and the strings in your if statements, you have to use the strcmp function. No other syntax will work in every instance.
Second, since you are using a variable as part of the .mat file name, you have to be certain to specify the first argument in save as specifically a .mat file. You can use square brackets [] to do the concatenation.
With those two changes, your code works:
alpha=input('input: ','s');
if strcmp(alpha,'A')
i=1;
elseif strcmp(alpha,'B')
i=4;
else
i=8;
end
x=[i+2 i];
filename = alpha;
save([filename '.mat'], 'x')
I also suggest using inputdlg rather than input, but that is my personal preference.
  2 Comments
azie
azie on 16 Jul 2015
The code is able to save the file name as the input alphabet but how about the name in the workspace? can it be change to the input alphabet too? For example my input is C. Using your code, filename was successfully named as C.mat but when it open, the name in workspace change to 'x'.
Star Strider
Star Strider on 16 Jul 2015
Your variable is ‘x’. You did not save ‘alpha’ in your original code, only ‘x’ if you want to save ‘alpha’ as well, your save call becomes:
save([filename '.mat'], 'alpha', 'x')

Sign in to comment.

Categories

Find more on Cell Arrays in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!