how to fulfill the matrix with for loop?
3 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposta accettata
Walter Roberson
il 9 Ago 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
2 Commenti
Paul Kaufmann
il 9 Ago 2021
TIL: repelem exists! Very nice, and also, obviously much cleaner than my approach.
Più risposte (1)
Paul Kaufmann
il 4 Ago 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
Vedere anche
Categorie
Scopri di più su Logical in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!