user input and save the the file name
조회 수: 5 (최근 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에서 Cell Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!