What does this expression means?

3 views (last 30 days)
I'm quite new in matlab. I got a program from a book and in it, there is a expresion that doesn't make sense to me. Because it uses a variable that was not previously defined. I don't understando how is this possible to use. Because ld is not decleared before, what is ld? What is the logic behind this? is it an array or a string or a integer? what is its initial value?
Here is the snip of code:
function[k_el,ld] = el_stif(ixl,x,y,matl)
% Function to compute element stiffness and assembly vector for triangle
for i = 1:2
ld(2*i-1) = 2*ixl(i) - 1;
ld(2*i ) = 2*ixl(i);
disp("LD is: " + ld + "and " + ld(2*i-1));
end
....

Accepted Answer

Walter Roberson
Walter Roberson on 6 Dec 2021
In MATLAB, when you assign into an array that does not already exist, then the array is created and the data type that is associated with the array after that is the same as the datatype of the first thing assigned into the array. Once the array exists, any other value to be assigned into the array is (if necessary) converted to the datatype determined by the first assignment.
MATLAB arrays grow dynamically if necessary, expanding according to the largest index that has been assigned at. If the assignment is done in a way that some slots have not been given an explicit value, then the slots will be assigned the value 0 (for numeric arrays)
ld(2*i-1) = 2*ixl(i) - 1;
The right hand side fetches the value of the array ixl indexed at the current value of i. When ixl is passed in, its data type is brought with it, so ixl(i) will have the datatype associated with ixl. The 2* stage is processed by converting the ixl(i) value to double precision (because the 2 is double precision), the multiplication of the two double precision is done, and the results are converted back to the datatype that ixl is. That might trigger some "saturation".
For example if ixl(1) is uint8 137 then for the multiplication that is converted to 137 double precision, the multiplication by 2 happens leading to temporary internal 274 that then has to be converted back to uint8. But the maximum uint8 is 255. The numbers do not wrap, unlike C or C++: instead the maximum uint8 value of 255 would be returned.
In this scenario you would then have a uint8 value and a subtraction by 1 double precision. The uint8 would be converted to double precision, subtraction would be done. Then comes conversion back to the original datatype. The internal double precision result might be negative: if so then because uint8 cannot hold negative numbers, 0 would be used.
All of this depends on the data type of the ixl array. If it were single precision floating point then that is what the end result would be, and the overflow / underflow of the integer types would not be relevant.

More Answers (0)

Products


Release

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!