Create mfile for a loop function

I was wondering if it is possible to create a function in mfile format for the bellow code (b0_T03_s is a table):
% to find x velocity and x position for bike #0
for i= 0:1:23;
b0_T03_s(2+i,25) = b0_T03_s(1+i,25) + b0_T03_s(1+i,23);
b0_T03_s(2+i,24) = b0_T03_s(1+i,24) + b0_T03_s(1+i,25) + (0.5*b0_T03_s(1+i,23));
end

2 件のコメント

Abderrahim. B
Abderrahim. B 2022 年 7 月 21 日
HI!
Do you mean to convert this snap of code into a MATLAB function?
Reem RA
Reem RA 2022 年 7 月 21 日
yes exactly

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

回答 (1 件)

Cris LaPierre
Cris LaPierre 2022 年 7 月 21 日

0 投票

Yes, it's possible. See this page on creating live functions in a live script using the Refactor tool.
The orginal and refactored code must be live scripts (.mlx file type) to use this tool, but once created, you can save as *.m if necessary.

6 件のコメント

Reem RA
Reem RA 2022 年 7 月 21 日
Thanks a lot, I will check the page that you have shared.
Reem RA
Reem RA 2022 年 7 月 21 日
Can you explain why am I keep getting this error:
"the variable b0_T03_s appears to change size on every loop iteration, consider preallocating for speed"
Is this because I am using an array in the function?
Cris LaPierre
Cris LaPierre 2022 年 7 月 21 日
No, it's because you are creating an array inside your for loop.
b0_T03_s(2+i,25)
The suggestion to preallocate means to create your variable of the desired final size first using dummy values (0s, 1s, nans, etc).
b0_T03_s = zeros(25);
for ...
You many need to adjust this code depending on if b0_T03_s has some values you want to keep, but this is the idea. In the end, what you are seeing is just a warning, not an error, so you can also just ignore it.
Reem RA
Reem RA 2022 年 7 月 21 日
Thanks a lot for your reply, appreciate it.
I am still getting the same error, in my case for the loop to start, I have to assign inital values for the first row, can you suggest an idea or refer some explanation to re-write this code?
function xf
b0_T03_sCopy(1,24) = b0_T03_sCopy(1,6);
b0_T03_sCopy(1,25) = b0_T03_sCopy(1,11);
for i= 0:1:23
b0_T03_sCopy(2+i,25) = b0_T03_sCopy(1+i,25) + b0_T03_sCopy(1+i,23);
b0_T03_sCopy(2+i,24) = b0_T03_sCopy(1+i,24) + b0_T03_sCopy(1+i,25) + (0.5*b0_T03_sCopy(1+i,23));
end
Cris LaPierre
Cris LaPierre 2022 年 7 月 22 日
You will need to keep in mind varible scope. Function only have access to the variables passed in as inputs or that are created inside the function.
Reem RA
Reem RA 2022 年 7 月 22 日
Thanks a lot Cris.

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

カテゴリ

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

タグ

質問済み:

2022 年 7 月 21 日

コメント済み:

2022 年 7 月 22 日

Community Treasure Hunt

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

Start Hunting!

Translated by