please help with work
2 views (last 30 days)
Show older comments
Dominic Garcia
on 18 Nov 2020
Edited: Rena Berman
on 7 May 2021
I have an assignment and I need it done. I am stuck and am very weak with strings...
4 Comments
Rik
on 18 Nov 2020
Edited: Rik
on 18 Nov 2020
Tackle the problem part by part:
"Your program must be able to ask user to enter a variable name"
Did you Google how you can do that?
"and display the user entered name"
Read the documentation for fprintf (or disp)
"check against the above rules"
You can do this two ways: test agains the entire list of allowed characters, or use Matlab functions that test properties of chars.
You get the idea. Which part did you try? Given that it is urgent, you must have already used Google, right?
Accepted Answer
Sean de Wolski
on 18 Nov 2020
v = ["Not Valid" "Valid"];
v(isvarname(input('enter variable name: ', 's'))+1)
2 Comments
Rik
on 18 Nov 2020
Nice one, a valid solution to the actual problem and very compact. And yet OP will still have to think for themselves to come up with an answer that their instructor will accept. Have an upvote from me.
Sean de Wolski
on 18 Nov 2020
I think this would also work elegantly for the engine:
potentialvarnames = ["hello" "he_llo" "2sw" "w?2" "x"];
matches(potentialvarnames, lettersPattern(1)+asManyOfPattern(alphanumericsPattern|characterListPattern("_")))
More Answers (1)
James Tursa
on 18 Nov 2020
Edited: James Tursa
on 18 Nov 2020
Use the input( ) function to get the user input. Use the optional 's' argument to get the input as a char string.
I'm assuming you can use the ASCII table provided to decide what range a character is in. Note that numbers and letters are in contiguous sections, which allows you to do the following:
Suppose you have stored the user input in a variable called vname. Then
vname(1) >='A' && vname(1) <= 'Z'
would check to see if the first character is an uppercase letter.
vname(1) >='a' && vname(1) <= 'z'
would check to see if the first character is a lowercase letter.
vname(1) >='0' && vname(1) <= '9'
would check to see if the first character is a decimal digit.
vname(1)=='_'
would check to see if the first character is an underscore
Etc.
See if you can write some looping code based on the number of characters in vname to check all of this.
2 Comments
James Tursa
on 18 Nov 2020
The basic idea would be to write a loop:
for k=1:numel(vname)
% code to check the vname(k) character here
end
See Also
Categories
Find more on Whos 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!