dustynrobots
dustynrobots

Reputation: 311

better way to do this in MATLAB?

I'm creating a 3x3 plot of subplots, and I want to have some options for display. Each subplot shows the torque vs. time for one degree of freedom (ex. knee flexion/extension), but I'm trying to give options of whether to show right and left, torque normalized by subject's mass, avg or not, etc. Right now I'm explicitly coding these options, but is there a better way to give me a choice of say: left only, not normalized, show avg? Hmmm

plotRight = 1;
normalizeByMass = 0;
   figure(1);
    for DOF = 1:9
    subplot(3,3,DOF);  
    if normalizeByMass
        if plotRight
            plot(x, torqueRnorm(:,:,DOF), 'r');
            hold on
        end
        if plotLeft
            plot(x, torqueLnorm(:,:,DOF));
            hold on
        end
    else
        if plotRight
            plot(x, torqueR(:,:,DOF), 'r');
            hold on
        end
        if plotLeft
            plot(x, torqueL(:,:,DOF));
            hold on
        end
    end
end
plot(x, torqueRmean(:,DOF), 'k', 'LineWidth', 2);
hold on
plot(x, torqueLmean(:,DOF), 'k', 'LineWidth', 2);
hold on
ylabel('Hip');
title('X');
axis tight;  

and the same thing for the next subplot...

Thanks

Upvotes: 0

Views: 89

Answers (1)

Simon
Simon

Reputation: 32873

Your approach is correct. It is much better to use variables and conditions as you did than to comment out lines manually each time you want to hide some plots, etc.

Now what you can do is wrapping everything in a function. And your parameters (plotLeft, plotRight…) would become the arguments of this function. Like this you hide the complexity and it frees your mind to build bigger things.

There are also little things you can do to improve the readability:

  1. Indent your code correctly. Matlab can help you: Ctrl-A Ctrl-I (or ⌘A ⌘I on mac) will fix the indentation in your whole file.

  2. hold on can be called just once after subplot

  3. use true and false for boolean values instead of 0 and 1

  4. you don't need a semicolon after figure, subplot, plot, xlabel, title, axis, and in general any instruction that returns nothing

Upvotes: 1

Related Questions