using sum() with a vector and increment

4 ビュー (過去 30 日間)
Isabella Kratzer
Isabella Kratzer 2018 年 4 月 11 日
回答済み: Isabella Kratzer 2018 年 4 月 11 日
Hi peeps, sorry about this rather simple question; I'm very new to this and cannot wrap my head around it. Dummy-Code:
A= [1 2 3 4 5; 6 7 8 9 10; 11 12 13 14 15]; %create 3x5 matrix
a = [2 3 4]; %row vector
b = A(1,:); %extract row 1 from Matrix A
c= b(a+1); %create vector from positions+1 defined with a
d=[1 c]; %create vector with 1 and positions
dsum=sum(A(1,d:d+1),1); %??????
Why does d:d+1 give me the first two positions of row 1 (and 2 and 3 if I change it so A(2,d:d+1))? I understand that : can be used to create vectors with certain increments, but it simply makes no sense to me. I'm sure there is a logical explanation. Anybody? Help is greatly appreciated.

採用された回答

Jan
Jan 2018 年 4 月 11 日
編集済み: Jan 2018 年 4 月 11 日
The colon operator ":" needs scalars as input. Then operation "vector:vector" is not defined. Unfortunately Matlab does not stop with an error, if you provide vectors as input, but only the first element is used.
v = [7,8,9]
v:v+1 % This is the same as: 7:7+1
% The rest of v is ignored
In your case only the first element 1 is used, such that "d:d+1" is the same as "1:2".
This behavior is a typical source of unexpected behavior in:
for k = 1:size(v)
when size(v,2) or numel(v) is meant.
  1 件のコメント
Guillaume
Guillaume 2018 年 4 月 11 日
Then operation "vector:vector" is not defined
I disagree, it is very well defined in that it is explicitly documented:
If you specify nonscalar arrays, then MATLAB interprets j:i:k as j(1):i(1):k(1).
However, yes, it would probably make more sense if matlab simply errored.

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

その他の回答 (1 件)

Isabella Kratzer
Isabella Kratzer 2018 年 4 月 11 日
Thank you both Jan and Guillaume!

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by