how to fulfill the matrix with for loop?
1 回表示 (過去 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.
0 件のコメント
採用された回答
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
2 件のコメント
Paul Kaufmann
2021 年 8 月 9 日
TIL: repelem exists! Very nice, and also, obviously much cleaner than my approach.
その他の回答 (1 件)
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
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!