user input and save the the file name
2 次查看(过去 30 天)
显示 更早的评论
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]
0 个评论
回答(1 个)
Star Strider
2015-7-16
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 个评论
Star Strider
2015-7-16
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')
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Workspace Variables and MAT Files 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!