How can I dynamically assign/access elements in a matrix with arbitrary dimensions?

I am creating a code to manipulate a matrix generated from an external file. I would like to make it so that the matrix could have arbitrary dimensions, e.g. in one file it might be just one dimension so listing all the elements could be done like:
A(:)
in another, it might have two dimensions, so listing the elements could be done like:
A(:,:)
if three,
A(:,:,:)
and so on. My problem is that I don’t know how (or maybe it is not possible) to make some general code to manipulate the matrix A. If I had know that A had dimension 3, I could just do something like
A(n,m,o)
But what I would like to do is something like
A(C)
where C is a list equal to [n m o] or [n m o … z].
Any ideas?
~Jensen~

回答 (1 件)

Jan
Jan 2013 年 1 月 15 日
編集済み: Jan 2014 年 7 月 15 日
Not matching the question exactly, but worth to mention:
A = rand(2,3,4) % Or: rand(2,3,4,5,4,3,2)
Index = cell(1, ndims(A));
Index(:) = {':'}; % BUGFIX: was {:}, thanks Walter and Jim
A(Index{:}) % Equivalent to: A(:, :, :)
Index{2} = 2:3;
A(Index{:});

6 件のコメント

? What is the line
Index(:) = {:};
intended to do?
Jan
Jan 2013 年 7 月 31 日
編集済み: Jan 2013 年 7 月 31 日
@Walter: Set all elements of the cell Index to the string ':'. It seems like I've forgot the quotes. There are some confusing facts about the magic indexing methods, so at least I'm obviously confused: The colon operator can (sometimes?) replaced by a string, as end can also. Does this work: A(':', ':') or A(:, 'end')? And it happened the other way around also, when : was working, also I'd expected that the string ':' is required. Finally I've posted "{:}" here, "{':'}" was meant and I perform further investigations. Most likely they match in my "magic string" thread.
@Jim: Please note, that flagging is a method to inform the admins about inappropriate messages, which conflict with the terms of use of this forum. I do not think that typos are a good reason to raise a flag.
Jim Hokanson
Jim Hokanson 2013 年 9 月 17 日
編集済み: Walter Roberson 2016 年 6 月 24 日
@Jan,
Thanks for the pointer on flags. Any other suggestion on how to mark something as needing to be fixed without having sufficient 'reputation' to fix it?
Jan
Jan 2013 年 9 月 17 日
編集済み: Jan 2013 年 9 月 17 日
@Jim: You can post a comment. Comments are a standard method in human communication to point out a specific detail.
But flags are used such rarely, that the forum does not suffer from a "misused" flag.
Matt
Matt 2014 年 7 月 10 日
Sharp! thanks
Chris
Chris 2016 年 6 月 24 日
You made my day! I 've been searching & trying for almost three hours...

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeMultidimensional Arrays についてさらに検索

質問済み:

2013 年 1 月 15 日

編集済み:

2016 年 6 月 24 日

Community Treasure Hunt

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

Start Hunting!

Translated by