apply function to each element in vector in matlab in matlab

To apply a function to each element of a vector in Matlab, you can use vectorization. This means performing an operation on an entire vector instead of individual elements one by one.

For example, if you have a vector A and you want to square each element, you can use the .^ operator as follows:

main.m
A = [1 2 3 4 5];
B = A.^2; % B will be [1 4 9 16 25]
53 chars
3 lines

Here, .^ is an element-wise power, which means that each element in A is raised to the power of 2.

You can also use other built-in functions such as sin, cos, exp, etc. For example:

main.m
A = [0 pi/4 pi/2 3*pi/4 pi];
B = sin(A); % B will be [0.0000 0.7071 1.0000 0.7071 0.0000]
90 chars
3 lines

Vectorization is a powerful tool in Matlab as it allows you to perform operations on large data sets quickly and efficiently.

related categories

gistlibby LogSnag