Accessing columns of array elements in a cell array without for loops
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Ted
am 19 Aug. 2017
Bearbeitet: Image Analyst
am 19 Aug. 2017
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 Kommentare
per isakson
am 19 Aug. 2017
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.
Akzeptierte Antwort
the cyclist
am 19 Aug. 2017
C2 = cellfun(@(x)x(:,1),C1,'UniformOutput',false);
5 Kommentare
Image Analyst
am 19 Aug. 2017
Bearbeitet: Image Analyst
am 19 Aug. 2017
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.
Weitere Antworten (1)
Image Analyst
am 19 Aug. 2017
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 Kommentare
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!