How do I make a loop for multiple identical actions?

I need to read some images in matlab like:
>> A1=dicomread('IM-0001.dcm');
>> A2=dicomread('IM-0002.dcm');
>> A3=dicomread('IM-0003.dcm');
>> A4=dicomread('IM-0004.dcm');
>> A5=dicomread('IM-0005.dcm');
I have 180 of those images. Is there a way to do it automatically so the first image is stored as A1 and the last as A180?
Cheers.

 채택된 답변

Sean de Wolski
Sean de Wolski 2012년 9월 11일
You don't need the cell at all then! So here are both ways:
1) Rather than preallocating img as a cell, preallocate it as a three d array:
img = zeros(128,128,170,'uint8');
for ii = 1:170
img(:,:,ii) = dicomread(etc)
end
2) Or you could take the cell and concatenate the elements along the third dimension using the comma-separated list expansion:
img = cat(3,img{:});
Welcome to MATLAB Answers!

댓글 수: 2

Great answer.
In addition: just remember to put ';' after 'end' otherwise matlab will keep showing you numbers of matrix for like 10 minutes :))
A mistake we all make very frequently :)
It gets me the worst when I miss the ';' once; it hangs around when I use the up arrow to pull up recent lines to run the same semicolon missing line again...

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

추가 답변 (1개)

Walter Roberson
Walter Roberson 2012년 9월 11일

0 개 추천

댓글 수: 3

I couldn't get it to work: I have tried the code:
for i=1:170
s1=int2str(i);
s2=strcat(s1,'.jpg');
img=dicomread('C:\Users\Tomek\Documents\MATLAB\dicoms\IM-0002-0001.dcm');
end
but got only empty tables.
Please more help about this.
Thanks.
Preallocate img as a cell array or 3d array (3d array only if all images the same size)
Then:
img = cell(170,1);
for ii = 1:170
img{ii} = dicomread(['C:\Users\Tomek\Documents\MATLAB\dicoms\IM-0002-' num2str(ii,'%04i') '.dcm'])
end
Now each element of img is the corresponding image:
imshow(img{120})
Tomislav
Tomislav 2012년 9월 11일
편집: Tomislav 2012년 9월 11일
ok, so i have made the 3d array like:
img=zeros(128,128,170); %images are 128x128 pixels
and then the code you provided, and it works.
Now i have a 170x1 cell with all the images inside.
How can I transform this into a 128x128x170 unit8 matrix?
Cheers.

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

카테고리

도움말 센터File Exchange에서 Images에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by