How to generalize 2 dimensions into n dimensions with a for loop?
Show older comments
Hi,
In 2D, I have a script like this:
bx = [min(x(1,:)) : ( (max(x(1,:)) - min(x(1,:))) /20 ) : max(x(1,:))];
by = [min(x(2,:)) : ( (max(x(2,:)) - min(x(2,:))) /20 ) : max(x(2,:))];
But here's the problem: x can have more than 2 rows. As a result, I want to have b's like:
bz = [min(x(3,:)) : ( (max(x(3,:)) - min(x(3,:))) /20 ) : max(x(3,:))];
ba = [min(x(4,:)) .....
....
....
So I need a for loop. I tried to do it like:
[M N] = size(x);
for s=1:1:M-1
b(s,:) = [min(x(s,:)) : (max(x(s,:))-min(x(s,:)))/20 : max(x(s,:))];
end
But I get the "Subscripted assignment dimension mismatch." error. I tried to ask this in http://www.mathworks.com/matlabcentral/answers/84556-how-can-i-create-a-specific-matrix-in-a-for-loop but since I couldn't clarify myself clearly, I didn't get the correct answer, the suggestion with doing this with linspace instead of colon didn't seem to work.
Edit: Another idea that comes to mind is this:
b = min(x(1,end)) : ((max(x(1,end))-min(x(1,end)))/20) : max(x(1,end));
but this doesn't generate a b matrix strangely. In the variable editor b seems like a 1x0 matrix with nothing inside if I do this statement instead.
The problem is not with the for loop, even if I don't do a for loop, and just write
b(1,:) = [min(x(1,:)) : ((max(x(1,:))-min(x(1,:)))/20) : max(x(1,:))];
I still get the same dimension mismatch error. So the problem has to do with the b(1,:) colon in this statement.
Accepted Answer
More Answers (0)
Categories
Find more on Loops and Conditional Statements 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!