0

I am looking for a way to create a dynamic functions in length with multiple inputs, tried doing it this way but it seems over kill am guessing slow too, is there a better way of doing this to be compact and fast.

Problem want to create a cos with inputs from nX3 matrix sum(A*cos(W*t + F)) where A, W, F are columns from the matrix sum them all up then divide by its norm. Here is what I have so far .

% example input can have n rows
A = [1 2 3; 4 5 6]; 
item.fre = 0;
item.amp = 0;
item.pha = 0;
items = repmat(item, size(A, 1), 1);
for i = 1:size(A, 1)
    items(i).fre = A(i, 1);
    items(i).amp = A(i, 2);
    items(i).pha = A(i, 3);
end

fun = @(t) sum(cell2mat(arrayfun(@(i) i.amp*cos(2*pi*t*i.fre + i.pha), items, 'un',0)));

% test run all this steps just to get a norm vector 
time = 1:10;
testSignal = fun(time);
testSignal = testSignal/norm(testSignal);
10
  • 3
    What is a dynamic function? Commented Jan 1, 2021 at 1:55
  • 2
    Why not use normal vectorization? Commented Jan 1, 2021 at 1:55
  • 2
    Do you understand what vectorization is? Matlab operates on variable sized inputs out of the box. It sounds like you're doing 10x work for no reason. Commented Jan 1, 2021 at 2:47
  • 1
    Just to clarify, if you have M rows in A N time samples, do you want to take the sum along the time or the A dimension? In other words, do you want an output of size M or size N? Commented Jan 1, 2021 at 2:53
  • 2
    Type in MATLAB: t=1:10, f=[1;2], f.*t. Look at the printed values. I’m sure you can expand from there out. It’s not nearly as complicated as you’re trying to make it. Forget about anonymous functions and structs and cell arrays. You can compute this in a single line. Commented Jan 1, 2021 at 2:54

1 Answer 1

1

I agree with a comment made by Cris Luengo to forget about anonymous functions and structures, you should try the simplest solution first. It looks like you're trying to add cosines with different amplitudes, frequencies, and phases. Here is how I would do it to make it very readable

A = [1 2 3; 4 5 6]; 
freq = A(:, 1);
amp = A(:, 2);
phase = A(:, 3);
time = 1:.01:10;
testSignal = zeros(size(time));
for i = 1:length(freq)
    testSignal = testSignal + amp(i) * cos(2*pi*freq(i) * time + phase(i));
end

testSignal = testSignal/norm(testSignal);
plot(time, testSignal)
grid on

You could eliminate the amp, phase, and freq variables by accessing the columns of A directly, but that would make the code much less readable.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the help, It was like milking ants for helpful information here....compute in a single line...that can sink ships

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.