Extracting parts of a matrix implicitly (without storing the matrix)
1 view (last 30 days)
Show older comments
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 Comment
Matt Fig
on 21 May 2011
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.
Accepted Answer
Walter Roberson
on 20 May 2011
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 Comment
Walter Roberson
on 21 May 2011
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.
More Answers (1)
James Tursa
on 21 May 2011
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:
0 Comments
See Also
Categories
Find more on Logical in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!