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

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

 採用された回答

Turlough Hughes
Turlough Hughes 2021 年 8 月 24 日
編集済み: Turlough Hughes 2021 年 8 月 24 日

1 投票

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 件のコメント

Turlough Hughes
Turlough Hughes 2021 年 8 月 24 日
You could also skip the loop:
x = 1:0.1:1.5;
vec = x + 1
vec = 1×6
2.0000 2.1000 2.2000 2.3000 2.4000 2.5000
Turlough Hughes
Turlough Hughes 2021 年 8 月 24 日
@Tanya Sharma, is this what you needed in the end then?
Tanya Sharma
Tanya Sharma 2021 年 8 月 25 日
@Turlough, thanks with the code. I am trying to fit it into my code but its not working still. My actual code is quite long and it consists of a function too to which I am supplying the value of ii. Can you help me with my code?
Turlough Hughes
Turlough Hughes 2021 年 8 月 25 日
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 2021 年 8 月 31 日
Thank you for the support Turlough. This solved my problem. Highly appreciate it.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by