Assigning the Nth element of Cell Array to another Array

조회 수: 9 (최근 30일)
tinkyminky93
tinkyminky93 2022년 6월 5일
편집: Voss 2022년 6월 5일
Hello, I have an cell array with 1000 rows and inside of this rows I have a 3 word. I am taking the 2nd element of this rows and want to assign these values to another array. In other words array_temp(i,1) = array(i,2). I want to do it with for loop. How can I do it?
  댓글 수: 1
Jan
Jan 2022년 6월 5일
편집: Jan 2022년 6월 5일
What does this mean: "inside of this rows I have a 3 word"?
Prefer to post some code, which reproduces a small set of test data.
What's wrong with this:
array_temp = array(:,2);
Why do you need a loop?

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

채택된 답변

Voss
Voss 2022년 6월 5일
편집: Voss 2022년 6월 5일
If array is a 1000-by-3 cell array, then you already know how to do it (here I'll use a 10-by-3 cell array):
% creating a 10-by-3 cell array of 'words':
array = mat2cell(char(randi(26,10,15)-1+'A'),ones(10,1),[5 5 5]);
disp(array);
{'PVCXI'} {'ZNTRT'} {'TSOZI'} {'KGKDP'} {'LDZKJ'} {'QEUIN'} {'LEFNA'} {'KKHYG'} {'XWEKS'} {'MXUUO'} {'KKODQ'} {'UQYZO'} {'OCZJK'} {'LKTBV'} {'DLDUU'} {'NDXWY'} {'ITHAE'} {'DFDHJ'} {'NRREZ'} {'LLRFH'} {'WKSJG'} {'BRKWE'} {'BRULF'} {'RALHF'} {'HNTDE'} {'QYBCZ'} {'IGFCE'} {'VVNNJ'} {'QSGME'} {'JYBVR'}
n_rows = size(array,1);
array_temp = cell(n_rows,1);
for i = 1:n_rows
array_temp(i,1) = array(i,2);
end
disp(array_temp);
{'ZNTRT'} {'LDZKJ'} {'KKHYG'} {'KKODQ'} {'LKTBV'} {'ITHAE'} {'LLRFH'} {'BRULF'} {'QYBCZ'} {'QSGME'}
But a for loop is not necessary:
array_temp = array(:,2);
disp(array_temp);
{'ZNTRT'} {'LDZKJ'} {'KKHYG'} {'KKODQ'} {'LKTBV'} {'ITHAE'} {'LLRFH'} {'BRULF'} {'QYBCZ'} {'QSGME'}
On the other hand, if array is a 1000-by-1 cell array with each element being a 1-by-3 cell array (again, using size 10 instead of 1000 for demonstration), you can do it with a for loop like this:
% creating the cell array of cell arrays:
array = num2cell(array,2);
disp(array);
{1×3 cell} {1×3 cell} {1×3 cell} {1×3 cell} {1×3 cell} {1×3 cell} {1×3 cell} {1×3 cell} {1×3 cell} {1×3 cell}
n_rows = size(array,1);
array_temp = cell(n_rows,1);
for i = 1:n_rows
array_temp(i,1) = array{i}(2);
end
disp(array_temp);
{'ZNTRT'} {'LDZKJ'} {'KKHYG'} {'KKODQ'} {'LKTBV'} {'ITHAE'} {'LLRFH'} {'BRULF'} {'QYBCZ'} {'QSGME'}
But again, an explicit for loop is not necessary:
array_temp = cellfun(@(x)x{2},array,'UniformOutput',false);
disp(array_temp);
{'ZNTRT'} {'LDZKJ'} {'KKHYG'} {'KKODQ'} {'LKTBV'} {'ITHAE'} {'LLRFH'} {'BRULF'} {'QYBCZ'} {'QSGME'}
If array is of some form besides one of these two, please post an example.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by