MATLAB: How to incremental increase values


The following code works to generate three values (cedar, fir and decid) that add to 1.0. I am new to matlab. How would I code this so that it would do the same thing for cedar = 0.01, cedar = 0.02, cedar = 0.03 and so on to cedar = 1.0 and output the values as a long table.
format bank cedar = 0; fir = 0; decid = 0; conifer = 0; for cedar = 0 while (conifer <= 1.0) fir = fir + 0.01; conifer = cedar + fir; decid = abs(1.0 – conifer); disp([cedar fir decid]); end end

Best Answer

  • Hi John,
    When including code in your question, please edit it so that it appears readable - just highlight the code portion(s) within your question and press the {}Code button.
    If you just want a long table (or matrix) then only slight changes to above your code would have to be made in order to get that long as you are okay with having each cedar group appear one after the other i.e. all rows with cedar=0 (with fir and decid summing to one), followed by all rows with cedar=0.01 (with fir and decid summing to 0.99), etc. In your code you have a for statement:
    for cedar = 0
    % do stuff

    Instead, you want to consider all possible cedar values from 0 to 1.0 with a step size of 0.01. The above line can easily be changed to do that:
    for cedar = 0:0.01:1.0
    % do stuff
    Note that how the middle value between the two colons dictates the step size for the lower and upper bounds of 0 and 1.0 respectively.
    Now since fir+decid+cedar must sum to one, so you can again do something similar to what you had before with a while loop, or you can add another for loop to iterate over the possible values of fir which can be anything from 0 to 1 less the value for cedar (since fir+decid+cedar=1 implies that fir+decid=1-cedar):
    for fir = 0:0.01:(1.0-cedar)
    % do other stuff
    The "other stuff" in the above is just the calculation of decid (easy from above equation with decid=1-cedar-fir) and the setting of some row in your output matrix, called treeDat say:
    treeData(j,:) = [cedar fir decid];
    which just sets all columns (indicated by the colon) of the jth row to the values of cedar,fir and decid. (j is just a local variable to keep track of which row you will be adding the data to at any iteration).
    Try the above and see what happens. You can always pre-allocate memory to the matrix before entering the loops (just need an estimate on how large it will be).