Combination of colon-operations in MATLAB

六月ゝ 毕业季﹏ 提交于 2019-12-23 19:25:55

问题


I have a question concerning the colon operator and expansion of vectors in MATLAB. My problem is to understand how the following line of code expands, to be able to use it for other sequences. The line of MATLAB code is:

a(1:2:5) = 1:-4:-7 

Note that a is not defined before the expansion. This returns the vector

a = 1 0 3 0 -7

I know how the colon operator works with {start}:{step}:{stop}, my problem is to understand how and why the combination of a(1:2:5)and 1:-4:-7 returns a vector of five elements with zeros in position 2 and 5?


回答1:


Whenever Matlab detects you're indecing to an element outside the current bounds of the matrix/array, it will automatically pad the missing elements with zeros:

>> clear b; b(10) = 5 
b =
    0     0     0     0     0     0     0     0     0     5

This feature is both very useful, and very dangerous. It is useful for the fact declarations can be made very easy, such as your own case. You can create a whole array of custom-made classes by issuing something like

myClassArray(500) = myClass(1, 2);

which is infinitely better than something like

% cannot pre-allocate (zeros() or ones() give double/uint8/..., not myClass)
for ii = 1:499
     myClassArray(ii) = myClass; % so, growing array
end
myClassArray(500) = myClass(1,2);

But, growing arrays can be hard to spot:

a = zeros(10,1);
for ii = 1:10
    a(ii+1) = rand;
end

which can make performance drop tremendously. Also, when you translate code prototyped in Matlab to a statically-typed language like C++, copying this code will result in buffer overflows and thus segfaults.

Now, going back to your case:

clear a;   a(1:2:5) = 1:-4:-7 

The 1:2:5 will expand to the array [1 3 5], and the 1:-4:-7 will give the values [1 -3 -7]. Since the variable a does not exist yet, Matlab will create a new one and fill the elements [1 3 5] with the values [1 -3 -7]. The indices that have been skipped in order to initialize variable a (namely, [2 4]) will then have been initialized automatically to zero.

If you're familiar with Python, it's a bit like the syntax to assign multiple values to multiple variables

x,y = 1,2

But in your Matlab case, these different variables are indices to a non-existent array, which requires "filling the holes with something" to make it a valid, consistent array.

Does this make things clear?




回答2:


when you define a(1:2:5), it creates a size 5 vector (zero-valued), and selecting odd indexed(3 of them exists) cells. 1:-4:-7 creates three values (not five). Finally your selected three cells are filled with data of 3 values coming from 1:-4:-7



来源:https://stackoverflow.com/questions/12105271/combination-of-colon-operations-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!