Reputation: 87
Can elements of a vector/matrix/tensor be selected using index relationships in MATLAB?
To clarify my question, I'll explain my problem.
I have a three-dimensional zero tensor D(m,n,p)
.
I now need to set the elements to 1
for which it holds that m == L-n+p+1
.
(L
is just a constant in this.)
Is there a way to do this in MATLAB without resorting to nested for-loops?
Thanks!
Upvotes: 1
Views: 55
Reputation: 221524
Approach # 1
This might easy and straight-forward for people to follow if not as efficient as the other two approaches -
[M,N,P] = ndgrid(1:m,1:n,1:p) %// create all indices using m, n, p
D(M == L-N+P+1) = 1 %// perform m == L-n+p+1 to get a logical array which you
%// can use to index into D and set the expected elements to 1
Approach # 2
RHS = bsxfun(@minus,1:p,[1:n]')+1+L; %//'# calculate `L-n+p+1`
D(bsxfun(@eq,[1:m]',permute(RHS,[3 1 2])))=1 %//'# perform equality `m == L-n+p+1`
Approach # 3
Permuting
earlier could be beneficial from performance point of view, so you can modify approach #2 on that -
RHS = bsxfun(@minus,permute(1:p,[1 3 2]),[1:n]) + L + 1
D(bsxfun(@eq,[1:m]',RHS))=1
Upvotes: 2