Search code examples
matlabmatlab-figurecontourf

How can I modify my code below to plot contour levels with a for loop?


The code below plots multiple contour maps at different locations on the Z axis specified by Zlevel. However, I have more than one Z data points of interest, hence I would like to use a for loop.

Zlevel=[0 1];

figure(1)
hold on 
[~,h1]=contourf(xx,yy,zz(:,:,1)); h1.ContourZLevel=Zlevel(1);
hold on 
[~,hh1]=contour(xx,yy,yy); hh1.ContourZLevel=h1.ContourZLevel;  
hold on 
[~,h2]=contourf(xx,yy,zz(:,:,2)); h2.ContourZLevel=Zlevel(2);
hold on 
[~,hh2]=contour(xx,yy,yy);hh2.ContourZLevel=h2.ContourZLevel;
hold off

I was thinking I could have something like this:

figure(1); hold on;
for i=1:length(Zlevel)
    [~,h(i)]=contourf(xx,yy,zz(:,:,i)); h(i).ContourZLevel=Zlevel(i); 
    hold on
    [~,hh(i)]=contour(xx,yy,yy); hh(i).ContourZLevel=Zlevel(i);
    hold on 
end
hold off

I have tried it and I can't make it work. I am probably not understanding matlab's object handling. So if someone could help me out and explain to me why I can't do what I am trying to do and point me in the right direction, I would really appreciate it!

Thanks!


Solution

  • I don't understand very well why you need 2 calls to contourf per plot, as the secodn should only create some bad lines on your image....

    Is this what you want?

    % dummy data
    [xx,yy,zz] = peaks;
    zz(:,:,2)=-zz(:,:,1);
    zz(:,:,3)=-2*zz(:,:,1);
    zz(:,:,4)=2*zz(:,:,1);
    
    
    
    Zlevel=[0 0.25 0.5 1];
    
    figure(1)
    hold on
    for ii=1:length(Zlevel)
        [~,h(ii)]=contourf(xx,yy,zz(:,:,ii)); h(ii).ContourZLevel=Zlevel(ii);
    
    end
    view(3)
    

    enter image description here