필터 지우기
필터 지우기

add numerical array as column or in cell array

조회 수: 2 (최근 30일)
Paul
Paul 2012년 11월 23일
댓글: Trung Hieu Le 2016년 6월 10일
How to add a numerical array
a=[1 2 3 4]
as row into my cell
C = |'a' 'b' 'c' 'd'|
|'e' 'f' 'g' 'h'|
|'i' 'j' 'k' 'l'|
|'m' 'n' 'o' 'p'|
so, that
C = |'1' '2' '3' '4'|
|'a' 'b' 'c' 'd'|
|'e' 'f' 'g' 'h'|
|'i' 'j' 'k' 'l'|
|'m' 'n' 'o' 'p'|
or as new column into cell C:
C = |'1' 'a' 'b' 'c' 'd'|
|'2' 'e' 'f' 'g' 'h'|
|'3' 'i' 'j' 'k' 'l'|
|'4' 'm' 'n' 'o' 'p'|
(the numerical values become strings).
AND: How to transform for example a 2x4 cell into a 1x8 (or 8x1) cell:
C= |'a' 'b' 'c' 'd'| ----> C = |'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h'|
|'e' 'f' 'g' 'h'|
or:----> C = |'a'|
|'e'|
|'b'|
|'f'|
|'c'|
|'g'|
|'d'|
|'h'|
I can solve these problems with for-loops, but imagine you have a huge size of the cell array, it is not very efficient. Is there an easier way? Thanks!

채택된 답변

Jan
Jan 2012년 11월 23일
편집: Jan 2012년 11월 23일
C = {'a' 'b' 'c' 'd'; ...
'e' 'f' 'g' 'h'; ...
'i' 'j' 'k' 'l'; ...
'm' 'n' 'o' 'p'};
a = [1 2 3 4];
tmp = sprintf('%g*', a);
tmp(end) = [];
aC = regexp(tmp, '*', 'split');
C_row = cat(1, aC, C); % Insert as row
C_col = cat(2, aC', C); % Insert as column
C2 = reshape(transpose(C), 1, [])
C3 = reshape(C, [], 1)

추가 답변 (1개)

Azzi Abdelmalek
Azzi Abdelmalek 2012년 11월 23일
편집: Azzi Abdelmalek 2012년 11월 23일
C = {'a' 'b' 'c' 'd'
'e' 'f' 'g' 'h'
'i' 'j' 'k' 'l'
'm' 'n' 'o' 'p'}
a=[1 2 3 4]
out=[num2cell(a); C]
%or
out=[num2cell(a') C]
% for third case
out=C(:)'
%or
out=reshape(C,1,[])
  댓글 수: 3
Azzi Abdelmalek
Azzi Abdelmalek 2012년 11월 23일
Ok Simon,
outv=[arrayfun(@(x) cellstr(num2str(x)),a); C]
or
outh=[arrayfun(@(x) cellstr(num2str(x)),a)' C]
Trung Hieu Le
Trung Hieu Le 2016년 6월 10일
It works well. Thanks a lot

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

카테고리

Help CenterFile Exchange에서 Multidimensional Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by