开发者

How can I use indexing on the output of a function? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

How can I index a MATLAB array returned by a function without first assigning it to a local variable?

I would like to use indexing on the output of a function. I use the textscan function to read very large text files (15 GB). The return of the textscan function in my case is a 1x1 cell array that contains a very large numeric array.

Instead of doing:

tmp = textscan(...);
final_result = mat2cell(tmp{1,1});

I would like to do:

final_result = mat2cell( textscan(...){1,1} );

If this would work, it would avoid the creation of the very large temporary variable tmp. Is th开发者_开发技巧ere another way to avoid the temporary variable?


In case you are still wondering, consider this example:

%# some function that returns a cell array (TEXTSCAN in your case)
myFunc = @() {rand(5,5)};

%# normally you would write
C = myFunc();
C = C{1,1};

Here is the cellarray-version of @gnovice answer in the linked question (ugly but works):

%# equivalent to: C = myFunc(){1,1}
C = subsref(myFunc(), struct('type','{}','subs',{{[1 1]}}))


You can't index the output of a function directly as you've shown. What you could do is change your code to the following:

final_result = textscan(...);
final_result = mat2cell(final_result{1,1});

Each element of a cell array contains pointers to other mxArrays. So, when extracting data from a cell array it is possible to simply have the output mxArray point to the same data. Using the final_result variable to hold the cell array as well as the contents extracted from it might be enough to tell the MATLAB JIT that it can optimize the code by not making an intermediate copy.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜