简体   繁体   English

使用 arrayfun 或其他方式创建动态 matlab function

[英]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.问题想要使用来自 nX3 矩阵sum(A*cos(W*t + F))的输入创建一个 cos,其中 A、W、F 是矩阵中的列,将它们全部相加,然后除以其范数。 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);

I agree with a comment made by Cris Luengo to forget about anonymous functions and structures, you should try the simplest solution first.我同意 Cris Luengo 关于忘记匿名函数和结构的评论,您应该先尝试最简单的解决方案。 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.您可以通过直接访问A的列来消除ampphasefreq变量,但这会使代码的可读性大大降低。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM