how to make a matrix with a function in each column in matlab

To create a matrix with a function in each column in MATLAB, you can create a function handle and then use arrayfun() or for loop to apply the function to each column.

Here is an example of how you can do it:

main.m
% Define the functions
function1 = @(x) x^2;
function2 = @(x) sin(x);
function3 = @(x) exp(x);

% Create a vector of x values
x = 1:5;

% Initialize an empty matrix
matrix = [];

% Apply the functions to each column
for i = 1:numel(x)
    column = [function1(x(i)); function2(x(i)); function3(x(i))];
    matrix = [matrix, column];
end

% Display the resulting matrix
disp(matrix);
382 chars
20 lines

In this example, we define three functions: function1, function2, and function3. We then create a vector x (in this case, it contains the values 1 to 5).

Next, we initialize an empty matrix matrix and use a for loop to loop through each element in x. Inside the loop, we apply each function to the current element in x, creating a column vector.

Finally, we concatenate each column vector to the matrix using the comma operator ,. After the loop, we display the resulting matrix.

Note that if you want to apply a different number of element-wise functions to each column, you may need to use a cell array instead of a matrix to accommodate different column lengths.

related categories

gistlibby LogSnag