Extracting parts of a matrix implicitly (without storing the matrix)

4 次查看(过去 30 天)
Hi,
Suppose I have a matrix [1 1 1; 2 2 2; 3 3 3] and suppose that I want to extract its second row. Of course I could do:
temp=[1 1 1; 2 2 2; 3 3 3];
temp(2,:)
But what if I don't want to store the matrix temporarily in temp? If I try the following:
[1 1 1; 2 2 2; 3 3 3](2,:)
I get an error message: "Error: Unbalanced or unexpected parenthesis or bracket." Is there a way to accomplish referring to a matrix implicitly (that is, without storing it or giving it a name)? Will this be faster than first storing the matrix in the variable temp? (I only want to do this because I speculate it may be faster.)
Thank you very much,
Andrew DeYoung
Carnegie Mellon University
  1 个评论
Matt Fig
Matt Fig 2011-5-21
There may be ways to avoid creating the temp matrix programmatically, depending on what you are doing. If you show more code we might be able to make a suggestion.

请先登录,再进行评论。

采纳的回答

Walter Roberson
Walter Roberson 2011-5-20
The time to store it in a temporary matrix will be negligible: it still has to create all the data structures for the variable except for the actual entry in the name tables.
Anyhow, you could try timing the following but I don't think you'll be overjoyed with the speed improvement:
subsref([1 1 1; 2 2 2; 3 3 3], struct('type', '()', 'subs', {{2, ':'}}))
  1 个评论
Walter Roberson
Walter Roberson 2011-5-21
You can also go through the trouble of:
rowN = @(A,N) A(N,:);
rowN([1 1 1;2 2 2; 3 3 3], 2)
but I think you will find this to be slower than a temporary variable.

请先登录,再进行评论。

更多回答(1 个)

James Tursa
James Tursa 2011-5-21
You can do what you show directly in Fortran, and kinda do it in C, but MATLAB has no official way of pointing to parts of other arrays. You will need to make the temp copy, or as Matt suggests, show more code to see if there is a way to do what you are attempting without making the temp copy. There is an unofficial way of pointing to the columns of a matrix (i.e. contiguous data) by Bruno Luong, but misuse can bomb MATLAB. You can find it here:

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by