Can I use a variable name to make logical comparison?
조회 수: 10 (최근 30일)
이전 댓글 표시
month = input('Enter the month: ');
months = [January, February, March, April, May, June, July, August, September, October, November, December];
k = find(months==month)
I have created the above array, months, and assigned each month to the number of days in it. I have asked a user to enter a month(in words). Now i want to compare the month the user entered with any of the months in the months array by using the find function, but it always compares the values withing the various months and not the variable names. Is there a workaround for this?
Thank you
댓글 수: 4
Image Analyst
2021년 11월 15일
Variable names can contain letters and numbers. Use whatever letters and numbers make for a descriptive variable name. Single letters are usually not descriptive except for really simple cases like x and y and k for a loop iterator.
You never defined January in your code so it doesn't know what that is. You need to assign it to a string or number
January = 'January'; % Character array.
January = "January"; % String Variable.
January = 1; % Double/number.
You can use numbers instead of strings if you want -- your choice.
답변 (3개)
Chunru
2021년 11월 15일
months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
%month = input('Enter the month: ');
month = "May"
k = find(months==month)
댓글 수: 5
Rik
2021년 11월 15일
You could use the string datatype (as Chunru suggested), or use a cellstr (a cell array of char vectors):
%month = input('Enter the month: ','s');
% ^^^^
% don't forget this
month='May';
months = {'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'};
k = find(ismember(months,month))
댓글 수: 3
Rik
2021년 11월 15일
They will not, nor should they. You should separate data from metadata. What do these arrays store? If the store average temperature per day, wouldn't MeanTemp make more sense as a variable name than January?
Image Analyst
2021년 11월 15일
You don't need find().
Simply use ismember():
%month = input('Enter the month: ','s');
% ^^^^
% don't forget this
month='May';
months = {'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'};
[~, index] = ismember(month, months)
댓글 수: 7
Stephen23
2021년 11월 19일
"so the truth is I'm learning Matlab using Matlab For Engineers by Chapman"
Over the years I have read several books about "learning MATLAB" and without exception they contained outdated, incorrect or misleading advice, and used terminology inconsistent with the MATLAB documentation.
A much more reliable source is: https://www.mathworks.com/help/matlab/getting-started-with-matlab.html
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!