1

To process data in MATLAB I have to execute a certain function, let's call it function(). Since there is much data to be processed, like large array Time or Voltage (but many more) I execute those one by one like this:

TimeNew = function(Time);
VoltageNew = function(Voltage);
... etc

So this is done around 10 times. Moreover, I have to do such a thing multiple times, resulting in around 30 lines of code which all do the same thing but to a different variable.

Is there a way to optimize this? I am using the most recent version of MATLAB (2015b) and have all toolboxes installed.

2 Answers 2

1

A possible solution could be to store the input array into a struct, them use that struct as input of the function.

In the function you can identify the number and content of each field by using fieldnames and getfiled built-in function.

The function could return a structure as output whose names can be made the same as the ones of the input struct.

In the example below, three arrays are generated and the function siply compute their square.

var_1=1:10;
var_2=11:20;
var_3=21:30;

str_in=struct('var_1',var_1,'var_2',var_2,'var_3',var_3)

str_out=my_function(str_in)

The function

function [str_out]=my_function(str_in)
f_names=fieldnames(str_in)
n_fields=length(f_names);

for i=1:n_fields
   x=getfield(str_in,f_names{i})
   str_out.(f_names{i})=x.^2;
end

Hope this helps.

Qapla'

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

9 Comments

Thanks, but won't I get the only variable str_out then?
Oh, and I think I need to move the function declaration in another .m file, right? I get the error that 'Function definitions are not permitted in this context'.
Yes, the function should be in a separate file. Wrt the output: yes, the output variable will be a struct with the same fields of the input structure
OK, I understand the output will be a struct as well. But can I just access a generated variable from that?
What di you mean with just access a generated variable from that?
|
0

You could try cellfun

allResultsAsACell = cellfun(@function, {Time,Voltage,...,varN});

This is equivalent to

allResultsAsACell{1} = function(Time);
allResultsAsACell{2} = function(Voltage);
...
allResultsAsACell{N} = function{VarN};

The issue is just matching up the indices with the values. I'm sure you could code those in as well if you needed (e.g. timeInd = 1; voltageInd =2; ...)

To see more on the cellfun method, type

help cellfun

into your MATLAB terminal.

Comments

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.