How to access a vector of a 3D array

I have a code :
%%%%%%%%%%%%%%%%%%%%%%%%
for i = 1 : 3
for j = 1 : 5
P{i,j} = rand(1,2);
end
end
P{1,:}(2)
% I want to use this to access a certain vector from this 3D matrix P
% But matlab told me "Bad cell reference operation". Can anyone tell me
% the reason and how to do it? Thanks a lot!

 채택된 답변

Jan
Jan 2012년 12월 20일

0 개 추천

Using a cell array is an inefficient representation. Better use a 3D array:
P = zeros(3, 5, 2);
for i = 1 : 3
for j = 1 : 5
P(i,j,:) = rand(1,2);
end
end
Now the indexing is trivial:
P(1, :, 2)

추가 답변 (2개)

Jianjian
Jianjian 2012년 12월 19일

0 개 추천

I know there is a stupid way to access this certain vector when j is small:
[P{1,1}(2), P{1,2}(2), P{1,3}(2), P{1,4}(2), P{1,5}(2)]
But it is not realistic when j is very large. Anyone can tell me a better way?
Walter Roberson
Walter Roberson 2012년 12월 19일

0 개 추천

P is not a 3D matrix. You could convert it to a 3D matrix by using cell2mat().
The P that you have established cannot be referenced the way you want with a simple operation. Consider using cellfun
cellfun(@(V) V(2), P)

댓글 수: 2

Jianjian
Jianjian 2012년 12월 20일
Although I still don't understand what does "V" mean after I checked the help file of "cellfun", I copied this line to the code, it works. Thanks!
Walter Roberson
Walter Roberson 2012년 12월 21일
The V does not mean anything to cellfun. The V is part of the anonymous function, @(V) V(2) that is being used. That means "This is an anonymous function that accepts a single parameter that we will temporarily refer to as "V"; what we should do when this function is called is to return the second element of the array currently named "V", which is to say the second element of whatever was passed in as the first parameter of the anonymous function."

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Structures에 대해 자세히 알아보기

질문:

2012년 12월 19일

Community Treasure Hunt

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

Start Hunting!

Translated by