Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

Create a dynamic matlab function using arrayfun or some other way

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...