how to fulfill the matrix with for loop?

2 次查看(过去 30 天)
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?
Thanks in advance.

采纳的回答

Walter Roberson
Walter Roberson 2021-8-9
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 个评论
Paul Kaufmann
Paul Kaufmann 2021-8-9
TIL: repelem exists! Very nice, and also, obviously much cleaner than my approach.

请先登录,再进行评论。

更多回答(1 个)

Paul Kaufmann
Paul Kaufmann 2021-8-4
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 个评论
esra kan
esra kan 2021-8-9
Hello Paul, thanks for your reply. I need 1x50. Also, this is just a sample, actually my data is very large.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by