how to fulfill the matrix with for loop?

1 vue (au cours des 30 derniers jours)
esra kan
esra kan le 4 Août 2021
Commenté : esra kan le 12 Août 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?
Thanks in advance.

Réponse acceptée

Walter Roberson
Walter Roberson le 9 Août 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 commentaires
Paul Kaufmann
Paul Kaufmann le 9 Août 2021
TIL: repelem exists! Very nice, and also, obviously much cleaner than my approach.
esra kan
esra kan le 12 Août 2021
Thank you, Walter!

Connectez-vous pour commenter.

Plus de réponses (1)

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

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by