Hello fellow coders, I ran into a predicament for a code to calculate the time differnce in A.M, and P.M
2 views (last 30 days)
function [dt]= timediff(TA,ap1,TB,ap2)
%This function will calculate the time difference between two times AM,PM
%Input:TA= a vector first element is hour second is minute, TB is the same
%but for the second time
%OUTPUT: Time differnce betweent the two specified times.
%First I am going to difine the the error
if TB>TA && ap1==ap2
error('Sorry time time travel does not exist try again and input correct times(TB is before TA)')
if ap1=='A.M' && ap2=='P.M'
So, overall, I'm gettin the error "Operands to the || and && operators must be convertible to logical scalar values.Error in timediff (line 8) if TB>TA && ap1==ap2"
I know exactly what matlab is saying, it saying that the ap1==ap2 are not logical scalars or numbers such as commonly used 1,2 or 3. The hw problemm says the the inputs for ap1 and ap2 NEED to be strings. So I'm trying my best to come up with a way to convert the strings to numbers. I've tried to incorportae str2num for the inputs but no dice. I need some guidance, and don't expect an answer I want to climb my way out of the hole while someone holds the rope. Thank you!
Hari Krishna Ravuri on 4 Nov 2019
“Operands to the || and && operators must be convertible to logical scalar values.Error in timediff (line 8) if TB>TA && ap1==ap2”
For character vector comparisons, consider using strcmp. The syntax of strcmp is
It returns a logical value 1, if both the character vectors are equal, else 0.
In your case, you may use as
strcmp(ap1,'A.M') && strcmp(ap2,'P.M')
Please refer https://in.mathworks.com/help/matlab/ref/strcmp.htmlfor more information regarding strcmp.
For handling date and time, you may consider using datetime. Please refer https://in.mathworks.com/help/matlab/ref/datetime.htmlfor more information regarding datetime.
Hope this helps!