How to save data in a vector for each loop indice?

1 vue (au cours des 30 derniers jours)
Tanya Sharma
Tanya Sharma le 24 Août 2021
Commenté : Tanya Sharma le 31 Août 2021
I am unable to save the data for each loop entry to a vector, as it gives the error that array indices must be integers. How do I save data in vec for each indice of 'ii'?
clear;
clc;
ii=1:0.1:1.5;
vec=zeros(length(ii),1);
for x = ii
sol = x+1;
vec(ii)=sol;
end

Réponse acceptée

Turlough Hughes
Turlough Hughes le 24 Août 2021
Modifié(e) : Turlough Hughes le 24 Août 2021
x = 1:0.1:1.5;
vec=zeros(size(x));
for ii = 1:numel(x)
sol = x(ii)+1;
vec(ii)=sol;
end
vec
vec = 1×6
2.0000 2.1000 2.2000 2.3000 2.4000 2.5000
  5 commentaires
Turlough Hughes
Turlough Hughes le 25 Août 2021
Another way would be to use a seperate counter:
ii=1:0.1:1.5;
vec=zeros(size(ii));
jj = 1;
for x = ii
sol = x+1;
vec(jj)=sol;
jj = jj + 1;
end
Tanya Sharma
Tanya Sharma le 31 Août 2021
Thank you for the support Turlough. This solved my problem. Highly appreciate it.

Connectez-vous pour commenter.

Plus de réponses (0)

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