Accessing columns of array elements in a cell array without for loops
4 ビュー (過去 30 日間)
古いコメントを表示
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
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.
採用された回答
the cyclist
2017 年 8 月 19 日
C2 = cellfun(@(x)x(:,1),C1,'UniformOutput',false);
5 件のコメント
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
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)
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!