anyway to cat specific column using horzcat?

Hi:
I have a cell array, the size is not determined, but each array is a 1000*3 matrix.
I want to merge the 3rd column of each array into a new matrix, is there anyway to do it?
below are what I have tried:
A{1}=rand(1000,3);
A{2}=rand(1000,3);
A{3}=rand(1000,3);
result= horzcat(A{:}(:,3))
or result= [A{:}(:,3)];
but Matlab reported error: Expected one output from a curly brace or dot indexing expression, but there were 3 results.
Thanks!
Yu

1 Kommentar

Rik
Rik am 2 Sep. 2019
As far as I'm aware, there is currently no way to do this directly in Matlab.
What you could do in this specific case is to cat A to the third dimension, and then select your data from the 3D array.

Melden Sie sich an, um zu kommentieren.

 Akzeptierte Antwort

Walter Roberson
Walter Roberson am 2 Sep. 2019

0 Stimmen

res = cell2mat(cellfun(@(x) x(:,3), A, 'uniform', 0));

4 Kommentare

Yu Li
Yu Li am 2 Sep. 2019
thank you Walter, your answer works. could you explain what does ('uniform', 0) mean here?
cellfun() can operate in two different modes. In the case where the function being applied always returns a scalar value, then it can create a numeric array with the same dimensions as the input cell, with each entry of the numeric array being the result of applying the function to one cell. For example you might do that with
cellfun(@mean2, A)
to get
[mean2(A{1,1}), mean2(A{1,2}), mean2(A{1,3}) ...]
However it is common when working with cells that you want to return a value that is not a numeric scalar. In that case, cellfun() can [usually] not return a plain array of results -- the outputs might not even be the same size for one thing. For that situation, you use the 'uniform' option with numeric value 0 (or false) to tell cellfun that the outputs are not uniformly scalar values. cellfun() handles that by wrapping the outputs into a cell, like
{F(A{1,1}), F(A{1,2}), F(A{1,3}) ... }
Guillaume
Guillaume am 2 Sep. 2019
your answer works
As I commented in dpb's answer, only if the cell array is a row vector.
res = cell2mat(cellfun(@(x) x(:,3), A(:).', 'uniform', 0));
This will work even with cell arrays that are column vectors.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Guillaume
Guillaume am 2 Sep. 2019

0 Stimmen

As others have said, no you can't do that with a single statement.
Assuming a cell array of any shape and size, rik's suggestion is probably the shortest to write:
result = cat(3, yourcellarray{:});
result = squeeze(result(:, 3, :));
The other option is cellfun indeed but without cell2mat if the cell array is not a row vector:
result = cellfun(@(m) m(:, 3), 'UniformOutput', false);
result = [result{:}];

Kategorien

Community Treasure Hunt

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

Start Hunting!

Translated by