What does tmp(k, n) command mean in matlab?
26 次查看(过去 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!