Hello fellow coders, I ran into a predicament for a code to calculate the time differnce in A.M, and P.M
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
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)')
end
if ap1=='A.M' && ap2=='P.M'
timediff= TB-TA+12;
elseif ap1==ap2
timediff=TB-TA;
end
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!
3 Kommentare
Elijah Smith
am 30 Okt. 2019
You can compare them if they are strings. Right now you have the variables defined as Char vectors not strings. I changed them to strings and turned it into a scrpt vs a function (just to test it) and it worked fine for me.
clear;clc
TB = 5; TA = 4; ap1 = "A.M"; ap2 = "P.M";
%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)')
end
if ap1=="A.M" && ap2=="P.M"
timediff= TB-TA+12;
elseif ap1==ap2
timediff=TB-TA;
end
Antworten (1)
Hari Krishna Ravuri
am 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
strcmp(charVector1, charVector2)
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!
0 Kommentare
Siehe auch
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!