Simply this sort of loop evaluates my function to the reference correctly:
for t = 2:length(x)
x(t) = x(t-1)+x(t);
end
tf = isequal(x,y);
tf
tf =
logical
1
While, surprisngly, this does not:
t = 2:length(x);
x(t) = x(t-1)+x(t);
tf = isequal(x,y);
tf
tf =
logical
0
Is there something obvious about Matlab I'm missing here?

回答 (1 件)

Stephen23
Stephen23 2019 年 1 月 25 日
編集済み: Stephen23 2019 年 1 月 25 日

0 投票

You are overwriting x values with the loop, so when you then try the vectorized code you have different x values. Clearly different input x values will give different output x values.
It works perfectly for me, when I do NOT overwrite the x vector values:
>> x = randi(9,1,7)
x =
1 8 9 7 7 7 4
>> for t = 2:length(x), y(t) = x(t-1)+x(t); end % assign to y, not x
>> y
y =
0 9 17 16 14 14 11
>> t = 2:length(x);
>> z(t) = x(t-1)+x(t); % assign to z, not x
>> z
z =
0 9 17 16 14 14 11

5 件のコメント

Oliver Dechant
Oliver Dechant 2019 年 1 月 25 日
Sure this is a fine answer, except that I need to overwrite the values. That behaviour is desired.
Torsten
Torsten 2019 年 1 月 25 日
編集済み: Torsten 2019 年 1 月 25 日
The result is not surprising to me.
While the loop works sequentially and already takes into account previously changed elements in the x-vector, the vectorized code gives the result of the following:
xold = x;
for t=2:length(x)
x(t) = xold(t-1) + xold(t);
end
Stephen23
Stephen23 2019 年 1 月 25 日
編集済み: Stephen23 2019 年 1 月 25 日
"... except that I need to overwrite the values. That behaviour is desired."
As far as I can tell, all you need is cumsum:
>> x = [1,8,9,7,7,7,4];
>> for t = 2:length(x), x(t) = x(t-1)+x(t); end, x
x =
1 9 18 25 32 39 43
>> x = [1,8,9,7,7,7,4];
>> x = cumsum(x)
x =
1 9 18 25 32 39 43
And, in case you were wondering, vectorizing cumsum withthout the cumsum function is certainly possible, but it would not be particularly simple or particularly efficient. cumsum is the way to go (better than using a loop too).
Torsten
Torsten 2019 年 1 月 25 日
I think the given recursion was just an example. "cumsum" won't be applicable in a more general case, I guess.
Jan
Jan 2019 年 1 月 25 日
@Torsten: If cumsum does not match the needs, filter is more powerful. E.g. an emultaion of cumsum:
x = randi(10, 1, 10)
a = cumsum(x)
b = filter(1, [1,-1], x)
isequal(a,b)

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

カテゴリ

ヘルプ センター および File ExchangeStartup and Shutdown についてさらに検索

タグ

質問済み:

2019 年 1 月 25 日

コメント済み:

Jan
2019 年 1 月 25 日

Community Treasure Hunt

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

Start Hunting!

Translated by