How can i save several 2-dimension-Matrices in a 3-dimension-Matrix
1 view (last 30 days)
Show older comments
I have a function "exsearch2": it gives me a 2-dimension matrix.
Now i want to save several of these 2-dimension-matrices in just one 3-dimension matrix. i did it this way (A, B and C are necessary for exsearch2):
for i=1:N
X(:,:,i)=exsearch2(A,B(i),C(i));
end
Number of columns is always the same, every time exsearch2 is executed. The Problem is: The number of lines is not always the same. I have no possibility to know the number of lines before i execute exsearch2. Matlab now tells me, that there is a subscripted assignment dimension mismatch and i can understand it. But what is the solution?
Example to understand: exsearch2 gives me for i=1 this matrix:
1 2
2 1
for i=2 it's this matrix:
2 3
1 2
1 3
What i want at the end is:
X(:,:,1) =
1 2
2 1
0 0
X(:,:,2)=
2 3
1 2
1 3
0 Comments
Accepted Answer
Stephen23
on 2 Sep 2015
Edited: Stephen23
on 2 Sep 2015
Try this:
for k=1:N
tmp = exsearch2(A,B(k),C(k));
X(1:size(tmp,1),:,k) = tmp;
end
This works by simply allocating the output of exsearch to a temporary variable tmp, and then only allocating to X as many rows as this tmp has. Also note that I changed the loop variable from i to k, because i and j are already defined as the imaginary unit, and it is best to avoid using them as variable names.
To improve performance you should also consider preallocating the array X instead of expanding it on every iteration. One easy way is to loop in reverse order:
for k=N:-1:1
More Answers (0)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!