Accessing columns of array elements in a cell array without for loops

조회 수: 4 (최근 30일)
Ted
Ted 2017년 8월 19일
편집: Image Analyst 2017년 8월 19일
I have a K-element cell array C1. Each element is an Nx3 array of doubles. How can I get a new cell array whose elements are the first column of each array in C1 using only logical indexing? For example, if C1 is {M1 M2 M3}, where M1=[1 2 3; 4 5 6; 7 8 9]=M2=M3; then I want a new cell array C2 that is {N1 N2 N3} where N1=[1;4;7]=N2=N3.
*Edit: My mistake, the K matrices do not all have the same number of rows (but they do all have 3 columns). See my comment below.
I can do this with a for loop:
for j=1:length(C1)
mat=C1{j}(:,1);
C2{j}=mat;
end
How can I do it without a loop?
  댓글 수: 2
per isakson
per isakson 2017년 8월 19일
is = [true(3,1),false(3,2)]
cellfun( @(c) c(is), C1, 'uni',false)
outputs
is =
1 0 0
1 0 0
1 0 0
ans =
[3x1 double] [3x1 double] [3x1 double]
However, I used array indexing to create the logical index. I give up.
Ted
Ted 2017년 8월 19일
Sorry, I should have specified that the K matrices are not necessarily all the same size; they each have 3 columns but an arbitrary number of rows. So they are not all Nx3 matrices, but rather nx3 matrices where n is different for each C{k}. My apologies.

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

채택된 답변

the cyclist
the cyclist 2017년 8월 19일
C2 = cellfun(@(x)x(:,1),C1,'UniformOutput',false);
  댓글 수: 5
Ted
Ted 2017년 8월 19일
I guess this is impossible using only logical indexing... disappointing. But this cellfun does the trick, thanks!
Image Analyst
Image Analyst 2017년 8월 19일
편집: Image Analyst 2017년 8월 19일
Did you see my solution below? It does it, at least for a known, fixed value of K. And you didn't explain why you are even using cells in the first place.

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

추가 답변 (1개)

Image Analyst
Image Analyst 2017년 8월 19일
Perhaps you want something like this:
% Setup:
% Define K random 3x3 matrices for the K M arrays.
% K = 3 in this example.
M1 = [1 2 3; 4 5 6; 7 8 9]
M2 = randi(9, 3, 3)
M3 = randi(9, 3, 3)
% Create C1 from the M's.
C1 = {M1 M2 M3}
% Solution:
% Use logical indexing to get Ns as the first column of the M's.
N1 = M1(logical([1, 0, 0, 1, 0, 0, 1, 0, 0]))'
N2 = M2(logical([1, 0, 0, 1, 0, 0, 1, 0, 0]))'
N3 = M3(logical([1, 0, 0, 1, 0, 0, 1, 0, 0]))'
% Create C2, a 1-by-3 cell array, that is the 3 column vectors
% (first columns of the M's) each in their own cell.
C2 = {N1 N2 N3}
celldisp(C2)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by