Creating a new matrix in a loop from a pre-determined matrix

Hello,
I want to create a new matrix "a" from a pre-determined matrix "x". I can do it like this if a and x have 3 rows:
ax = ((max(x(1,:))-min(x(1,:)))/10);
ay = ((max(x(2,:))-min(x(2,:)))/10);
az = ((max(x(3,:))-min(x(3,:)))/10);
But I want to make this with a for loop in a more general and compact way.
for j=1:1:numel(x)
a(j) = ((max(x(j,:))-min(x(j,:)))/10);
end
If I try to do it like this I get dimensional mismatch errors. It seems notoriously hard for me to create matrices in for loops with pre-determined set of conditions in MATLAB.

 Accepted Answer

a=[1 5 3;4 10 6;7 11 19;20 30 50]
c=(max(a')-min(a'))/10
ax=c(1)
ay=c(2)
az=c(3)

2 Comments

Thanks but I need to make this with a for loop because number of rows of x can change, thus I need to make it more general. For example it could be 5 instead of 3. If I could make a for loop, I would just write 1:numel(x) which could generate what I want.
This is general
a=[1 5 3;4 10 6;7 11 19;20 30 50]
c=(max(a')-min(a'))/10
% c contains all your values

Sign in to comment.

More Answers (1)

Your for-loop isn't right. The 'numel' will give you too many indices. It should be
n = size(x,1);
a = zeros(n,1);
for j = 1:n
etc.

1 Comment

Yes, thanks but it still won't work because of what's inside the for loop I guess. I need to change a(j) part I assume.

Sign in to comment.

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!