Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected behavior while using end to grow arrays

Tags:

arrays

matlab

while building a video array from a directory of images I encounter unexpected behavior. Original code:

vid = [];
for i =startframe:endframe
    image = [directoryOfImages ,'\', images_names{1,i}];
    vid(:,:,:,end+1) = imread(image);
    waitbar((i-startframe) / (endframe-startframe));
end

Then I ran this code to check thing up:

a = []; size(a)
a(end+1) = 1; size(a)

The first size was [0, 0] and the second size was [1, 1]. The same expected behavior I got in this code:

b = []; size(b)
b(:,end+1) = 1; size(b)

The first size was [0, 0] and the second size was [1, 1]. But in this code, something weird happened:

c = []; size(c)
c(:,:,end+1) = 1; size(c)

while here the first size was [0,0] and the second one was [1,1,2]. This was very unexpected. I printed c and I got this:

>>c
c(:,:,1) =

     0

c(:,:,2) =

     1

Finally, I ran this script:

c=[]; c(:,:,end)=1; size(c)

and I got [1, 1].

can someone explain what is going on here? when I use c=[] do I get an empty array with the size of [0,0,1]? so how come size(c) doesn't mention it? and why when I use c(:,:,end)=1; its size is not [1,1,1]? and what about when I use c(:,:,:,end)=1?

like image 817
Avizipi Avatar asked Aug 31 '17 09:08

Avizipi


1 Answers

This is just MATLAB choosing what to display.

In MATLAB, matrices are infinite dimensional. As a nice example, lets try your b:

b = []; 
b(:,end+1) = 1; 

As you know, you can query the size of an specific dimension with size. E.g. size(b,2) returns 1. But what does size(b,12345) return?, well, it returns 1 also, as matrices are infinite dimensional. In the 12345th dimension, the size of b is 1.

However, what horrible would the display function be, if every time you type size(b) it outputs an infinite amount of dimensions! Thus when displaying, MATLAB defaults to displaying 2 dims OR N-dims, where N is the furthest dimension with data on it (non-singleton dimension).

Thus, what you are seeing with your c example is weird behaviour by the display function, not the size function. size(c,3) returns 1. This is caused also by the [] only setting the size of the first two dimensions to zero, to avoid having a MxPx0 variable when filling it up (c(:,:,end)=img, what happens with end ?), which is essentially an empty variable.

like image 153
Ander Biguri Avatar answered Oct 23 '22 05:10

Ander Biguri