Why are is the zeros or zero(size) function in a for-loop function?

์กฐํšŒ ์ˆ˜: 11 (์ตœ๊ทผ 30์ผ)
Rayell
Rayell 2023๋…„ 9์›” 28์ผ
๋‹ต๋ณ€: Dyuman Joshi 2023๋…„ 9์›” 28์ผ
This is what i am trying to answer:
Compute ๐‘ฆ = cos 2 ๐‘ฅ for x-values from 0 to ๐œ‹ (at least 100 values of x). Do this (i) with a for-loop
There are two different ways to do the y output. Im confused on that part
% Compute y= cos2x, with 100 values of x between 0 and pi
% (i) for-loop
% Create vectors
x = linspace (0,pi,100); % 100 values of x from 0 to pi
% Initialize the output vector y
y = zeros(1,100);
% y = zeros(size(x))^2
%Compute y-values using a for-loop
for i = 1:100
y(i) = cos(x(i))^2;
end

๋‹ต๋ณ€ (1๊ฐœ)

Dyuman Joshi
Dyuman Joshi 2023๋…„ 9์›” 28์ผ
"Why are is the zeros or zero(size) function in a for-loop function?"
y = zeros(1,100);
This is called Pre-allocation. It is done to improve the code execution time.
Another method to obtain the output is to vectorize the code - Vectorization
x = linspace(0,pi,100);
%Take the cos() of values in x and square every element.
y = cos(x).^2;

์นดํ…Œ๊ณ ๋ฆฌ

Help Center ๋ฐ File Exchange์—์„œ Loops and Conditional Statements์— ๋Œ€ํ•ด ์ž์„ธํžˆ ์•Œ์•„๋ณด๊ธฐ

์ œํ’ˆ


๋ฆด๋ฆฌ์Šค

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by