# how to fulfill the matrix with for loop?

3 views (last 30 days)
esra kan on 4 Aug 2021
Commented: esra kan on 12 Aug 2021
Hello there,
xxx=[1 3 8 20 30 40 50];
inn=[0.1 0.3 0.7 0.2 0.4 0.6 0.5];
for i=1:(length(xxx)-1)
l=xxx(i);
u=xxx(i+1);
ve(:,l:u)=inn(i);
i=i+1;
end
I want to create a vector which has 0.1 from 1 to 3, 0.3 from 4 to 8, 0.7 from 9 to 20 and so on. However, the code gives 0.1 from 1 to 2, 0.3 from 3 to 7 and so on. i=i+1 does not work. How can i make it correct?
I have a second question.
In my original code, xxx=[0 3 8 20 30 40 50]; it starts with zero, Matlab says that "Subscript indices must either be real positive integers or logicals." since it reuires to start from 1. But according to my aim, it must start from 0. Could you also help me to correct it, please?

Walter Roberson on 9 Aug 2021
xxx=[0 3 8 20 30 40 50];
inn=[0.1 0.3 0.7 0.2 0.4 0.6 0.5];
count = diff(xxx);
ve = repelem(inn(1:length(count)), count);
ve
ve = 1×50
0.1000 0.1000 0.1000 0.3000 0.3000 0.3000 0.3000 0.3000 0.7000 0.7000 0.7000 0.7000 0.7000 0.7000 0.7000 0.7000 0.7000 0.7000 0.7000 0.7000 0.2000 0.2000 0.2000 0.2000 0.2000 0.2000 0.2000 0.2000 0.2000 0.2000
##### 2 CommentsShowHide 1 older comment
esra kan on 12 Aug 2021
Thank you, Walter!

### More Answers (1)

Paul Kaufmann on 4 Aug 2021
the intended dimension of ve is not quite clear to me, but maybe this is what you want:
x = [0 3 8 20 30 40 50]
n = [ 0.1 0.3 0.7 0.2 0.4 0.6 0.5]
arb = 3; % arbitrary dimension, up to you
dx = diff(x);
v = [];
for i = 1:numel(dx)
v = [v ; ones(dx(i),arb)*n(i)]
end
This method above is computationally very inefficient, but it gets the job done, if your matrix is relatively small.
This is the output result:
>> v
v =
0.1000 0.1000 0.1000
0.1000 0.1000 0.1000
0.1000 0.1000 0.1000
0.3000 0.3000 0.3000
0.3000 0.3000 0.3000
0.3000 0.3000 0.3000
0.3000 0.3000 0.3000
... ... ...
>> whos v
Name Size Bytes Class
v 50x3 1200 double
##### 1 CommentShowHide None
esra kan on 9 Aug 2021
Hello Paul, thanks for your reply. I need 1x50. Also, this is just a sample, actually my data is very large.