What does tmp(k, n) command mean in matlab?
23 ビュー (過去 30 日間)
古いコメントを表示
I got this code for dct transform matrix, but it isnt correct. I dont understand the tmp calling:
function [ C ] = dct_mtx( N )
for k = 0:N-1
for n = 0:N-1
tmp(k+1,n+1) = cos((0.5+N)*k*pi/N);
end
end
tmp(1,:) = tmp(1,:) / sqrt(2);
C = tmp;
end
回答 (3 件)
KSSV
2018 年 10 月 5 日
unction [ C ] = dct_mtx( N ) % this is to call a function
for k = 0:N-1 % loop for k variable (row)
for n = 0:N-1 % loop for n variable (column)
tmp(k+1,n+1) = cos((0.5+N)*k*pi/N); % calculation stored in tmp(k+1,n+1)
end % end loop
end % end loop
tmp(1,:) = tmp(1,:) / sqrt(2); % this will replace the first row of tmp with (tmp first row)/sqrt(2)
C = tmp; % tmp is assigned to variable C
end
3 件のコメント
Stephen23
2018 年 10 月 5 日
編集済み: Stephen23
2018 年 10 月 5 日
MATLAB does not require variables to be declared before being indexed into: when they are first referred to the variable will be implicitly created. Here is a simple example which works without error, even though X does not exist in the workspace:
>> X(3) = 6
X =
0 0 6
You can see that MATLAB simply created a variable big enough to include the index used, and filled the unused elements with zeros. So the rather badly written code in your question uses that feature:
function [ C ] = dct_mtx( N )
for k = 0:N-1
for n = 0:N-1
tmp(k+1,n+1) = cos((0.5+N)*k*pi/N);
end
end
On the very first loop iteration tmp does not exist, but the first time it is referred to (with indexing) MATLAB creates it, with whatever class the data has.
However I would NOT recommend doing this: this method is susceptible to bugs caused by an existing variable of the same name. It can be trivially avoided by preallocating before the loops. Your example is also pointlessly slow because it expands the array on each loop iteration, which means the array must be moved in memory:
Summary: Do NOT learn from that pointlessly inefficient code.
0 件のコメント
HOUSSAM Touhrach
2021 年 11 月 23 日
I write this code but the error message is :
Invalid expression. When calling a function or indexing a variable, use parentheses. Otherwise, check for mismatched delimiters.
function [P,A] = ExtrusionPresure(ys,D0,D,k,n,Om)
ts=0:50;
P = 1;
for i=2:length(ts)
P = 2 .* ys .* log(D0./D) + FonctionA(n,Om).* k .* (ts(i)).^n) * (1-(D./D0).^(3 .* n));
end
end
1 件のコメント
Stephen23
2021 年 11 月 23 日
Your parentheses are mismatched:
P = 2 .* ys .* log(D0./D) + FonctionA(n,Om).* k .* (ts(i)).^n) * (1-(D./D0).^(3 .* n));
% 0 1 0 1 0 1 2 10 -1 0 1 0 1 0-1
% ^ maybe you
% should delete this
% one
参考
カテゴリ
Help Center および File Exchange で Performance and Memory についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!