필터 지우기
필터 지우기

Using a cell array and a for loop

조회 수: 1 (최근 30일)
Riri
Riri 2014년 1월 28일
댓글: Riri 2014년 1월 28일
Hey guys, I have to do a cell array to strore some information about an animal and use a for loop to display that information and the result should look like this:
Identification number: 1
Gender: M
Weight: 400
Age: 4
Treatment: 0
I've tried many thing and I dont get how to have to columns. This is what i've tried.
rat_cell = {'number', 'sex', 'weight', 'age', 'treatment', 1, 'M', 400, 4, 0};
for i = 1:5
disp(rat_cell(i,:))
     for j = 1:5
     disp (rat_cell (j,:));
end
end
I dont get why it doesnt show 2 columns like its supposed to. Thanks

채택된 답변

Amit
Amit 2014년 1월 28일
You can use you code with a little modification: First of all, you're showing first cell and then 5 cell from the beginning. This is not what you want.
rat_cell = {'number', 'sex', 'weight', 'age', 'treatment'; '1', 'M', '400', '4', '0'}; % Note I changed the numbers to string
for j = 1:5
disp([rat_cell{1,i} ': ' rat_cell{2,i}]);
end

추가 답변 (2개)

Andrei Bobrov
Andrei Bobrov 2014년 1월 28일
use struct array
rat_cell = {'number', 'sex', 'weight', 'age', 'treatment', 1, 'M', 400, 4, 0};
a = reshape(rat_cell,5,[])';
out = struct(a{:});

Azzi Abdelmalek
Azzi Abdelmalek 2014년 1월 28일
편집: Azzi Abdelmalek 2014년 1월 28일
There are many errors in your code:
Why nested loop? you are using display function 30 times!
i=1:5 and j=1:5 , you will never reach the 6th element
rat_cell(i,:) : what does that mean?
The correct code:
rat_cell = {'number', 'sex', 'weight', 'age', 'treatment', 1, 'M', 400, 4, 0};
for i = 1:5
disp([rat_cell{i} ':' num2str(rat_cell {i+5})]);
end
But for such problems, it's better to use what Andrei proposed
  댓글 수: 3
Azzi Abdelmalek
Azzi Abdelmalek 2014년 1월 28일
편집: Azzi Abdelmalek 2014년 1월 28일
rat_cell is 1x10 cell array. There is one row and 10 columns. You needed to put the first cell near the sixth cell and the second near the seventh, and so on.
Riri
Riri 2014년 1월 28일
Ya you are right, i just checked that out. Thanks for the clarification.

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by