Search code examples
matlabbar-chartmatlab-figure

How can I update ZData in a bar3 plot?


I'm trying to update the ZData of a bar3 plot:

z = [[1, 2]; [3, 4]];
z_new = [[1, 2]; [3, 3]];
h = bar3(z);% works fine until here

set(h, 'ZData', z_new);

I then get following errors:

Warning: Error creating or updating Surface
 Error in value of property  ZData
 Array is wrong shape or size 
Warning: Error creating or updating Surface
 Error in value of property  ZData
 Array is wrong shape or size 

They don't crash the program but the data of the existing plot gets deleted instead of overwritten.

I don't understand why this happens, since the matrices are obviously the same size.


Solution

  • I don't understand why this happens, since the matrices are obviously the same size.

    They are not of the same size. bar3 creates a custom ZData entry from the z argument provided. Displaying the ZData entry for z=[[1, 2]; [3, 4]];

    h.ZData
    
    ans =
    
       NaN     0     0   NaN
         0     1     1     0
         0     1     1     0
       NaN     0     0   NaN
       NaN     0     0   NaN
       NaN   NaN   NaN   NaN
       NaN     0     0   NaN
         0     3     3     0
         0     3     3     0
       NaN     0     0   NaN
       NaN     0     0   NaN
       NaN   NaN   NaN   NaN
    
    
    ans =
    
       NaN     0     0   NaN
         0     2     2     0
         0     2     2     0
       NaN     0     0   NaN
       NaN     0     0   NaN
       NaN   NaN   NaN   NaN
       NaN     0     0   NaN
         0     4     4     0
         0     4     4     0
       NaN     0     0   NaN
       NaN     0     0   NaN
       NaN   NaN   NaN   NaN
    

    You could update ZData by constructing a matrix in the above format and filling z_new data in the correct places and it should work. If your intention is to just overwrite the old plot you're better off using h = bar3(z_new);