matlab code help..
4 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(2 个)
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
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
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.
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!