I am not able to use eval for a string of variables in order to evaluate these variables in a multidimensional array.
2 views (last 30 days)
Show older comments
I am not able to use eval for a string of variables in order to evaluate these variables in a multidimensional array. In fact, I want to use one of these index variables as ':'. My code is as following:{
X is a multidimensional array
%%Initialisation of 15 variables
for i=1:length(X) % length(X)=15
eval(sprintf('i%d = 1', i));
double(strcat('i',num2str(i)));
end
for i=1:length(X)
||||| node(i) = X(eval(sprintf('i%d,',[1:length(X)]))); % this doesnt work.|||||||
}%%
Also I want to use one of these variables as ':' to take all the dimension of the considered index. if the statement above work, then i will be able to initiate one of these variable as ':'
4 Comments
Stephen23
on 6 Sep 2018
Edited: Stephen23
on 6 Sep 2018
"In fact i am coding on tensors and i want to write a function to extract fibers without writing the whole X(1,1,1,1,1,1,1,1,1,1,1,1,1,1,:)"
Then use the method I showed in my answer, which is much simpler than what you are trying to do.
And in future, remember that eval forces you into writing slow, complex, buggy code that is hard to debug. Avoid using eval:
Accepted Answer
Stephen23
on 6 Sep 2018
Edited: Stephen23
on 6 Sep 2018
Just use a cell array of indices, which is much simpler and much more efficient. And no loop is required either:
X = randi(9,5,4,3,2) % some ND array
C = repmat({1},ndims(X)); % indices in cell array
...
X(C{:})
This is exactly equivalent to writing
X(C{1},C{2},C{3},...,C{end})
thus giving you the indexing that you require. You can easily change the (index) values in C, it is very straightforward, e.g.:
C{2} = 3;
It also makes it easy to specify ranges of a dimension, e.g.:
C{2} = 1:6;
or to get all of any dimension, e.g.:
C{2} = ':';
"i want to write a function to extract fibers without writing the whole X(1,1,1,1,1,1,1,1,1,1,1,1,1,1,:)"
Now you know how easy this is:
C = repmat({1},1,ndims(X));
C{end} = ':';
X(C{:})
Read these to know how it works:
7 Comments
More Answers (0)
See Also
Categories
Find more on Operators and Elementary Operations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!