Why does this loop create a horizontal array instead of a vertical array?

I know this may seem a really simple question but I just can't seem to work this one out when consulting the manual.
Within my code I have the following loop to work out the difference between sensor readings:
for i = 1 : size(xVal)
df([i]) = yVal(i+1) - yVal(i);
End
xVal is a line number and yVal is a sensor reading.
But for some reason, rather than creating a vertical array of difference values, a horizontal array is created and before it is complete MATLAB throws up an error stating "Index exceeds matrix dimensions" (I assume this error is because the horizontal array goes beyond a value MATLAB can handle.)
How can I change this loop so that a vertical array is created? (I also assume that this would overcome the "Index exceeds matrix dimensions" error?)
Any help is greatly appreciated.

 採用された回答

Alexandra
Alexandra 2012 年 10 月 23 日

0 投票

Why don't you try it with the function diff? It's easier and very quickly...

2 件のコメント

Alexandra
Alexandra 2012 年 10 月 23 日
Also you have to put the right dimension when you use size function, especially on a for
for i = 1 : size(xVal,1) % -> Rows
Red Beard
Red Beard 2012 年 10 月 23 日
This is exactly what I have been looking for. I couldn't find this function in the manual!!!
Thank you.

サインインしてコメントする。

その他の回答 (1 件)

Sachin Ganjare
Sachin Ganjare 2012 年 10 月 23 日
Probably you have preallocated array df as maybe zeros(x,1). It should be:
df = zeros(1,x);
x is number of elements in array df
Hope it helps!!!

カテゴリ

ヘルプ センター および File Exchange で Loops and Conditional Statements についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by