matlab code help..

조회 수: 4 (최근 30일)
abishai
abishai 2012년 3월 4일
Hi everyone
This is my first post and I am totally new to Matlab, started a couple of weeks back been practicing and all but already got an assignment to come up with a Matlab code. I have a pretty simple question
Say I have a set of data like x = [-2 3 -4 5 -2 5 -3 10 8 9 ]. The set represents basically +ve and -ve peaks. I am trying to get a loop to do the difference between each 2 points along the vector set(difference between -2&3 3&-4 -4&5 5&-2 and....so on).Could someone give me some ideas of how to get around this...would really appreciate the help
thank you

답변 (2개)

Wayne King
Wayne King 2012년 3월 4일
Welcome to MATLAB! One of the great things about MATLAB is that it handles matrices (and vectors) easily. I would recommend you try to avoid loops as much as you can. There is a MATLAB function diff() that does just want you need.
x = [-2 3 -4 5 -2 5 -3 10 8 9];
y = diff(x);
Of course, if your homework is specifically to write a loop to do this, then let me give you some hints (I don't want to just write the loop for you)
The basic assignment you need is something like:
y(n) = x(n+1)-x(n);
where y is the output and x the input. Now that takes the difference of elements in a particular order, the same order as diff(). If you want it the other way:
y(n) = x(n)-x(n+1);
Since MATLAB indexes from 1, you have to think about the range of your n in the for loop. You want to start at 1, but think about how far the n go grow since you are trying to access x(n+1)
  댓글 수: 3
Image Analyst
Image Analyst 2012년 3월 4일
a(i+1) is longer. It goes from a(2) to a(35). Try this
b = [a(i) 0] - a(i+1)
or similar. Also it's not recommended to use i (the imaginary constant) as a variable.
Jan
Jan 2012년 3월 4일
Yes, it works without a loop. Did you try "diff(a)"?
What does "not coming out right" exactly mean? It is much better to explain the error or problem in the forum instead of only mention that there is one.

댓글을 달려면 로그인하십시오.


abishai
abishai 2012년 3월 4일
solved it Just had to take off the following b = a(i)
thanks a lot guys still got to finish the code..its going to take a while

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

태그

아직 태그를 입력하지 않았습니다.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by