Solution/MATLAB

[Cody] Problem 2447. Musical Note Interval 1 - Diatonic Scale

2023. 8. 22. 20:00

Assuming a simple diatonic C scale, calculate the interval (integer) between two notes (provided as strings). By applying numbers to the notes of the scale (C,D,E,F,G,A,B,C = 1,2,3,4,5,6,7,8), intervals can be calculated. Because a unison is defined as one rather than zero, you add one to the numerical difference. The intervals are defined as:

C - C: perfect unison, 1

C - D: major second, 2

C - E: major third, 3

C - F: perfect fourth, 4

C - G: perfect fifth, 5

C - A: major sixth, 6

C - B: major seventh, 7

For example, if the input is {'C','G'} the output will be a perfect fifth: 5-1+1=5. For input {'E','A'} the output will be a perfect fourth: 6-3+1=4.

For intervals that wrap around the scale, add seven to the resulting negative number to obtain the correct interval. For example, for {'A','C'} the output will be a major third: 1-6+1=-4, -4+7=3.


function interval = note_interval(notes)

  no1 = converter(double(notes{1}))
  no2 = converter(double(notes{2}))
  
  if no2 - no1 < 0
    interval = no2 - no1 + 8
  else
    interval = no2 - no1 + 1
  end
end

function convertion = converter(n)

  if n >= 67
    convertion = n - 66;
  else
    convertion = n - 59;
  end
end