問題描述
如何創建一個行矩陣,其元素是我的 while 循環的迭代 (How to create a row matrix whose elements are the iterations of my while loop)
對 matlab 非常陌生,我在語法上遇到了困難。我想執行一個 while 循環,其中每個 nth 迭代將是我的矩陣的 nth 元素,所以基本上我想到的是:
f=[];
s:=1:
while s~=10 do
f(s):=s.^2;
s:=s+1;
end_while
這是正確的代碼嗎?
參考解法
方法 1:
You can do it without the while
loop:
f=[1:9].^2
If you want to use a loop, you can do:
f=[];
s=1;
while s~=10
f(s)=s.^2;
s=s+1;
end
Edit following Matt comment below
The code you've written contains 4 errors (three of them are of the same type):
s:=1;
to assign a value to a var use simply =
, that is s=1
(:
not needed)
- to close the
while
loop, useend
(end_while
is not a MatLab statement)
Also, as suggested by Matt, you can use a for
loop:
f=[];
for s=1:9
f(s)=s^2
end
Anyway, I suggest you to use the first approach (f=[1:9].^2
).
Hope this helps.
Qapla'