
본 포스팅은 MATLAB의 Mathworks에서 제공하는 Onramp cody문제 해결의 마지막 포스팅입니다. 총 2개의 cody 문제와 솔루션, 리뷰 내용이 담겨 있습니다.
The file cars.mat contains a table named cars with variables Model, MPG, Horsepower, Weight, and Acceleration for several classic cars.
Load the MAT-file. Given an integer N, calculate the output variable mpg.
Output mpg should contain the MPG of the top N lightest cars (by Weight) in a column vector.
이 문제를 통해서는 행렬 혹은 테이블 자료를 기존의 내장된 함수로 sorting하는 방법에 대해서 학습할 수 있었습니다. 간단히 문제를 소개해보자면 cars.mat 파일을 load한 뒤, 가벼운 순서대로 N개의 차량 MPG값을 열벡터로 변환하여 반환해야 합니다.
문제 해결에 앞서서 sortrows 함수에 대해 간략히 정리해보고 넘어가겠습니다.

B = sortrows(A)
B = sortrows(A)는 행렬 A에 대하여 첫 번째 열의 요소를 기준으로 오름차순으로 행을 sorting하여 정렬해줍니다.
B = sortrows(A,column)
B = sortrows(A,column)은 column번째 열의 요소를 기준으로 오름차순으로 행을 sorting하여 정렬해줍니다. column에 정수가 아닌 [x,y]와 같은 행벡터를 입력할 시, x번째 열의 요소를 기준으로 오름차순 sorting한 뒤 2차적으로 y번째 열의 요소를 기준으로 sorting을 진행합니다.
B = sortrows(...,direction)
B = sortrows(...,direction)는 앞서 입력한 행렬의 sorting의 방향을 설정할 수 있습니다. 예를 들어, sortrows(A,[2,5],{'ascend', 'descend'})는 행렬 A에 대하여 2번째 행에 대하여 오름차순으로 sorting한 뒤. 5번째 열의 요소에 대하여 2차적으로 내림차순으로 정렬합니다.
[B,index] = sortrows(...)
[B,index] = sortrows(...)를 이용하면 행의 정렬한 순서를 index 열벡터를 통하여 확인할 수 있습니다. 예를 들어 [E,index] = sortrows(A,4,'descend') 를 실행시키면,


행렬 A에 대하여 4번째 열의 요소를 기준으로 내림차순으로 정렬한 뒤, index에서는 기존의 행과 비교하여 새로 정렬된 정보를 얻을 수 있습니다.
S = sortrows(cars,'Weight')
먼저 문제에서 주어진 cars table에서 Weight열을 기준으로 오름차순 sorting합니다.
S_MPG = S(1:N,"MPG")
이후 sorting된 테이블 S에 대하여 1~N번째 행의 MPG열의 값을 인덱싱하여 S_MPG table에 저장합니다. 이 때 저장된 형식은 table형식입니다.
mpg = S_MPG.MPG
마지막으로 table형식으로 저장한 S_MPG에 MPG항목을 인덱싱하여 열벡터로 반환해줍니다.
이 과정을 거친 최종 solution은 다음과 같습니다.
function mpg = sort_cars(N)
load('cars.mat')
S = sortrows(cars,'Weight')
S_MPG = S(1:N,"MPG")
mpg = S_MPG.MPG
end
Given a vector a, find the number(s) that is/are repeated consecutively most often.
For example, if you have
a = [1 2 2 2 1 3 2 1 4 5 1]
The answer would be 2, because it shows up three consecutive times.
If your vector is a row vector, your output should be a row vector. If your input is a column vector, your output should be a column vector. You can assume there are no Inf or NaN in the input. Super (albeit non-scored) bonus points if you get a solution that works with these, though.
위 문제는 Onramp cody 가장 마지막 문제로 익숙하지 않은 다른 내장함수를 사용하기 보다는 기존의 함수를 이용하여 해결할 수 있는 알고리즘 문제에 가까운 문제였습니다. 알고리즘이 간단하기 때문에 해설은 생략하고 솔루션만 첨부하겠습니다.
function val=longrun(a)
[xsize,ysize] = size(a);
times = 1; // Max consecutive times
value = []; // vector that has the value of number which appeared the most in a row or column vector
i = 1;
while i <=(max(xsize,ysize)-1)
j = 1;
times_comparing = 1;
while a(i) == a(i+j)
times_comparing = times_comparing + 1;
j = j + 1;
if (i+j) > max(xsize,ysize) // prevent error for logical operation in a line 9,while.
break
end
end
if times_comparing == times
value = [value,a(i)]
end
if times_comparing > times
times = times_comparing;
value = [a(i)]
end
i = i + j;
end
if times == 1
value = [value,a(end)]
end
if ysize == 1
value = (value)';
end
val = value
end
이번 포스팅을 마지막으로 Mathworks에서 제공하는 MATLAB Onramp Practice cody를 마치겠습니다. 감사합니다!
* Reference : https://kr.mathworks.com/help/matlab/ref/double.sortrows.html