Search code examples
arraysmatlabmatrixoperatorsoperation

Entry level question about Matlab array operation


Hey guys. I have this question to ask. In C programming, if we want to store several values in an array, we implement that using loops like this:

j=0; //initialize  
for (idx=1,idx less than a constant; idex++)  
{  
    slope[j]=(y2-y1)/(x2-x1);  
    j++;  
}  

My question is in Matlab do we have any simpler way to get the same array 'slope' without manually increasing j? Something like:

for idx=1:constant  
    slope[]=(y2-y1)/(x2-x1);

Thank you!


Solution

  • Such operations can usually be done without looping.

    For example, if the slope is the same for all entries, you can write

    slope = ones(numRows,numCols) * (y2-y1)/(x2-x1);
    

    where numRows and numCols are the size of the array slope.

    If you have a list of y-values and x-values, and you want the slope at every point, you can call

    slope = (y(2:end)-y(1:end-1))./(x(2:end)-x(1:end-1)
    

    and get everything in one go. Note that y(2:end) are all elements from the second to the last, and y(1:end-1) are all elements from the first to the second to last. Thus, the first element of the slope is calculated from the difference between the second and the first element of y. Also, note the ./ instead of /. The dot makes it an element-wise operation, meaning that I divide the first element of the array in the numerator by the first element of the array in the denominator, etc.