Sampling with vectors at the same time
조회 수: 2 (최근 30일)
이전 댓글 표시
Hello,
its a simple question, but i havent managed to solve it:
I have to sample a vector and the matlab doesn't understandme and prompts:
??? Error using ==> mtimes
Inner matrix dimensions must agree.
I wanted to sample a SUM (cos(2*pi*d*A) )where A is a vector of many degrees value, so I have:
function sample(d)
A = [1,2,3,....]
SUM (cos(2*pi*d*A) )
end
and the input is:
d=[1:1:20]
How can I make understand first vector is a sampling and second is a vector of values? (The idea is plotting (sample,d) )
The fact is that the expresion of the vector is a real for each value of d so I should expect something returning results of the SUM of different d's like:
Columns 1 through 11
1 2 3 4 5 6 7 8 9 10 11
Columns 12 through 20
12 13 14 15 16 17 18 19 20
But it doesn't understand each
Thank you
댓글 수: 7
채택된 답변
Dr. Seis
2013년 2월 25일
편집: Dr. Seis
2013년 2월 25일
Try this:
d = 1:20;
A = [24,34,56,66,86];
plot(d,arrayfun(@(x)sum(cos(2*pi*A*x)),d))
Obviously, in this simple case, the answer will always be 5 for all d since we are dealing with integer multiples of 2*pi (and there are only 5 elements in A), but I think this is what you are looking for.
댓글 수: 2
추가 답변 (4개)
Image Analyst
2013년 2월 24일
편집: Image Analyst
2013년 2월 24일
What is SUM? Is it a custom function you wrote, or an array of yours, because it's not the built-in MATLAB sum() function because MATLAB is case sensitive.
Perhaps you meant something like this:
A = 1:20
d=[1:1:20]
cosA = cos(2*pi*d.*A)
theSum = sum(cosA)
Note the .* instead of * between d and A to do an element by element multiplication, not a matrix multiplication like you were trying to do.
댓글 수: 8
Image Analyst
2013년 2월 26일
Alfonso, you need to read the getting started guide. You can't just type all that code into a single m-file because you can't have a script followed by a function in the same file. The main program can be in one m-file, and the other function in another m-file, OR if you want them to be in the same file, then you must have a function name at the beginning of the file with the same name as the m-file. For example if it's test.m, then your code would be
function test()
dMain = [1:1:20]
for k = 1 : length(dMain)
% Call sample() once for each value of d
theSumMain(k) = sample(dMain(k));
end
theSumMain % Print to command window
function theSum = sample(d)
A = 1:20;
cosA = cos(2*pi*d.*A);
theSum = sum(cosA);
If it's like that they can all be in the same m-file. I guess I assumed that you knew this.
Azzi Abdelmalek
2013년 2월 24일
편집: Azzi Abdelmalek
2013년 2월 24일
Maybe you mean indexing
v=[2 3 5 4 10 20]
d=[2 3 1 4 5 6]
new_v=v(d)
참고 항목
카테고리
Help Center 및 File Exchange에서 Startup and Shutdown에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!