# creating 3d array from images

47 views (last 30 days)
Xen on 9 Sep 2014
Commented: Xen on 9 Sep 2014
Hello, I am trying to read and copy a series of 5 images into a 3d array, where each image should have a 'thickness' of 13 pixels. When run I get this error:
Undefined function or variable 'B2'.
Error in U (line 20)
I=cat(3,B1,B2,B3,B4,B5);
Why B1 image is copied, but not B2 (and I suppose the rest)? Here is the code. Thanks!
I=zeros(256,256,100);
n=13;
for i=1:5
x=[int2str(i) '.png'];
if exist(x, 'file')
B{i}=A{i}(:,:,1);
B{i}=repmat(B{i},[1 1 n]);
else
fprintf('File %s does not exist.\n', x);
end
end
I=cat(3,B1,B2,C3,B4,B5);

Geoff Hayes on 9 Sep 2014
Xenios - I think that you mean to use B{2} in place of B2 (though I'm not sure how B1 passed - could you have defined it elsewhere?). Try replacing your line
I=cat(3,B1,B2,C3,B4,B5);
with
I=cat(3,B{1},B{2},B{3},B{4},B{5});
Note how the above line also uses B{3} rather than C3.

David Young on 9 Sep 2014
B2 is the name of a variable, which has not been given a value. It appears that B1 was given a value in some code that isn't shown in your question. Anyway, these variables aren't used - instead you need to use the elements of the cell array B.
Assuming that C3 is just a typo, it looks like you mean, for the final line
I = cat(3, B{1}, B{2}, B{3}, B{4}, B{5});
David Young on 9 Sep 2014
You may also want to consider putting something in the else part of the condition, for when a file is missing - e.g. B{i} = []. For generality and conciseness, you could also replace the final line with
I = cat(3, B{:});

Xen on 9 Sep 2014
Thanks for the help guys! It solved the problem. Yes, C3 was a typo. It really is strange though, because B1 was not defined anywhere else, and this code works for
I=cat(3,A1,A2,A3,A4,A5);
or
I=cat(3,B1,A2,A3,A4,A5);
but not for the rest of any other Bi values. So I didn't assume that brackets are needed.
(Geoff got the accepted answer as he replied first)

Xen on 9 Sep 2014
By the way, what's the best way for including the I=cat(...) into the loop?
Thanks.
##### 2 CommentsShowHide 1 older comment
Xen on 9 Sep 2014
Hi. Thanks for that, it really works. This is not part of a huge code, so naming the variables is not too important! I will also pass the comments to the people who had suggested the use of these functions... Anyway, I apologise as I just started using MATLAB. This code is the only one that works as expected, so I am currently Ok with it! Hopefully all images are perfectly orderly named in their folder.

### Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by