What does tmp(k, n) command mean in matlab?
조회 수: 28 (최근 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!