Arithmetic Code: Need help Identifying where my problem is
조회 수: 3 (최근 30일)
이전 댓글 표시
Problem prompt:
Develop a function ArithGeo(vec) that takes the vector of numbers stored in vec and returns "Arithmetic" if the sequence follows an arithmetic pattern or return "Geometric" if it follows a geometric pattern. If the sequence doesn't follow either pattern return ‐1. An arithmetic sequence is one where the difference between each of the numbers is constant, where as in a geometric sequence each term after the first is multiplied by some constant or common ratio. Arithmetic example: [2, 4, 6, 8] (difference between each number is 2) and Geometric example: [2, 6, 18, 54] (constant ratio = 3). Assume only positive numbers may be entered as parameters, 0 will not be entered, and no array will contain all the same elements. Examples: ArithGeo(5,10,15) outputs "Arithmetic"; ArithGeo(2,4,16,24) outputs ‐1; and ArithGeo(2,4,8,16) outputs “Geometric”.
My answer:
vec=input('Positive real non-repeating numbers')
n=size(vec)
for i=2:n
for j=3:n
if vec(i)-vec(i-1) ~= vec(j)-vec(j-1)&&(vec(i)-vec(i-1))/(vec(i)) ~= (vec(j)-vec(j-1))/2*(vec(i));
disp('-1')
break
elseif vec(i)-vec(i-1) == vec(j)-vec(j-1)
disp('Arithmetic')
elseif (vec(i)-vec(i-1))/(vec(i)) == (vec(j)-vec(j-1))/2*(vec(i))
disp('Geometric')
end
end
end
Comments:
It is sort of working. When I run it, it displays up to size of my vector. For example I put 2 4 8 16 . So it should display geometric but it doesn't. It doesn't even give me an error. So I'm not sure what's going on
댓글 수: 0
채택된 답변
Stephen23
2015년 3월 15일
편집: Stephen23
2015년 3월 17일
Doing this in a loop is poor use of MATLAB, and you are making it far too complicated. MATLAB is a high-level language, which means you should learn how to vectorize your code instead. For example, we could divide a vector of values by the previous values like this:
>> A = [2,6,18,54];
>> A(end:-1:2) ./ A(end-1:-1:1)
ans =
3 3 3
With fully vectorized code one operation is required, without any loop! Note how some some simple indexing is used to select which values are being divided. Similarly you can use diff for finding the difference:
>> B = [2,4,6,8];
>> diff(B)
ans =
2 2 2
To determine the final output you can then think about using some functions like diff and all, or perhaps using unique and numel.
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!