How to add elements to a vector in matlab - matlab

I've looked around on the internet a bit and cannot seem to find the answer to this question. I want to declare a vector in matlab and then have a for loop that will add an element to the vector each time I go through the for loop.
This is what I've tried and it doesn't seem to be working
vector[];
for k = 1 ; 10
%calculate some value
%calculated value stored in temp variable
vector(k) = temp;
end
This does not work. Does anybody know how to solve this issue?

As ypnos said, you don't need to declare the vector variable upfront. For example if you did:
vector(50) = 1;
MATLAB would make a vector of length 50 with the 50th value being 1. If you want to improve performance and want to create a vector of the proper size beforehand then do the following:
vector = zeros(10, 1);
The code as you have it (as long as you fix the loop as ypnos said) will work, except for how you declare vector, which is not correct. I bet you are getting the error message: "Error: Unbalanced or unexpected parenthesis or bracket." You do not specify whether a variable is a matrix/vector in MATLAB.

vector = [vector; temp];
or
vector(end+1) = temp;

Related

peak finder for multidimensional array

I'm trying the following and is not working. Could someone help me on this?
A=rand(1,4,5);
peak_num=zeros(5,4);
for w=1:5
peak_num(w,:)=peakfinder(A(1,1:4,w))
end
peak_num;
in this case the vector of peaks found for each w has a different size.
Thanks
I haven't really taken a look at the internals of the peakfinder function but if you make sure that it does not output a vector with more than 4 elements this is a workaround:
A=rand(1,4,5);
peak_num=zeros(5,4);
for w=1:5
temp = peakfinder(A(1,1:4,w));
peak_num(w, 1:length(temp) ) = temp
end
peak_num;
It sets the first elements to the return values and keeps the others being zero.

Looping through columns and rows without using Indexing in matlab

I'm fairly new to matlab and I'm currently working on MATLAB to create a loop that will go through each column and each row and then increment A and B as it goes. I know that there's indexing which you can do but I'd like to learn how to do it step by step. I've come up with the pseudo code for it but I'm struggling with the actual syntax in MATLAB to be able to do it.
Pseudocode:
For columns i 1-300;
Increment A
For rows j 1-4
Increment B
End
End
My actual code that I've been trying to get to work is:
%testmatrix = 4:300 Already defined earlier as a 4 row and 300 column matrix
for i = testmatrix (:,300)
for j = testmatrix (4,:)
B=B+1
end
A=A+1
end
I'm not 100% sure how I'm supposed to format the code so it'll read testmatrix(1,1) all the way through to testmatrix (4,300).
Any help would be greatly appreciated!
You could let it run through the first row to get the right column, then through that column. But you can't feed your running value from the matrix:
[rows cols] = size(testmatrix); %// rows=4, cols=300
for i = 1:cols
for j = 1:rows
temp = testmatrix (j,i); %// contains the element of your matrix at (j,i)
B=B+1;
end
A=A+1;
end
The semicolons ; suppress the output to the command line. Remove them if you want to output A and B at each step.
Here, temp will cycle through the elements (1,1) through (4,300) and you can do whatever you want with them. Note that this is generally an inefficient way to do most things. Matlab supports greatly efficient vectorized calculations, which you should use. But unless I know what exactly you're trying to achieve, I can't really help you with that. (If all you want is A and B's final values, it's as easy as A=A+cols;B=B+cols*rows;.)

(simple?) error with findpeaks and if loop

I'm trying to find the local maxima of a data set using the findpeaks() function and so far I have this code:
[pks, locs] = findpeaks(signal);
max_times = zeros(size(locs));
if n = 1:size(locs);
max_times(n) = (times(locs(n)));
end
What am I trying to do? Well I have a set of signal data and the corresponding times. I want to get the local maxima values and output two vectors; the maxima signal values and the times that they occured.
How am I doing it? I'm using the findpeaks function to find the peaks (pks) and location (locs) of the maxima. I'm then setting up a blank array the same length as the locs vector and then using an if loop to fill up the empty max_times(n) vector with the times that the maxima occur
The problem? I keep getting this errorExpression or statement is incomplete or incorrect. about my if loop. I don't understand what this means/ how do I solve this problem/ edit my code to get it to do what I want?
Thanks for any help!
What you are thinking is totally wrong.
If is not a loop its a conditional statement
what you want here is a for loop
for n = 1:size(locs)
% your code
end
also times take two parameter and you should figure it out yourself what it should be

Function to find entries with same maximum value in a vector

In my project I need a function which returns the index of the largest element of a given vector. Just like max. For more than one entry with the same maximum value (which occurs frequently) the function should choose one randomly. Unlike max.
The function is a subfunction in a MATLAB Function Block in Simulink. And the whole Simulink model is compiled.
My basic idea was:
function ind = findOpt(vector)
index_max = find(vector == max(vector));
random = randi([1,length(index_max)],1);
ind = index_max(random);
end
But I got problems with the comparison in find and with randi.
I found out about safe comparison here: Problem using the find function in MATLAB. Also I found a way to replace randi([1,imax],1): Implement 'randi' using 'rand' in MATLAB.
My Code now looks like this:
function ind = findOpt(vector)
tolerance = 0.00001;
index_max = find(abs(vector - max(vector)) < tolerance);
random = ceil(length(index_max)*rand(1));
ind = index_max(random);
end
Still doesn't work. I understand that the length of index_max is unclear and causes problems. But I can not think of any way to know it before. Any ideas how to solve this?
Also, I'm shocked that ceil doesn't work when the code gets executed?? In debug mode there is no change to the input visible.
I thought about creating an array like: index_max = abs(vector - max(vector)) < tolerance; But not sure how that could help. Also, it doesn't solve my problem with the random selection.
Hopefully somebody has more ideas or at least could give me some hints!
I am using MATLAB R2012b (32bit) on a Windows7-64bit PC, with the Lcc-win32 C 2.4.1 compiler.
Edit:
Vector usually is of size 5x1 and contains values between -2000 and zero which are of type double, e.g. vector = [-1000 -1200 -1000 -1100 -1550]'. But I think such a simple function should work with any kind of input vector.
The call of length(index_max) causes an system error in MATLAB and forces me to shut it down. I guess this is due to the strange return I get from find. For a vector with all the same values the return from find is something like [1.000 2.000 1.000 2.000 0.000]' which doesn't make any sense to me at all.
function v= findOpt(v)
if isempty(v)
return;
end
v = find((max(v) - v) < 0.00001);
v = v(ceil(rand(1)*end));
end
I was indeed overloading, just like user664303 suggested! Since I can not use objects in my project, I wanted an function that behaves similar, so I wrote:
function varargout = table(mode, varargin)
persistent table;
if isempty(table) && ~strcmp(mode,'writeTable')
error(...)
end
switch mode
case 'getValue'
...
case 'writeTable'
table = ...
...
end
end
Wanted to avoid passing the dimensions for the table in every call and thought it would be enough if the first call initializes the Table with mode='writeTable'. Looks like this caused my problem.
No problems after changing to:
if isempty(table)
table = zeros(dim1,dim2,...)
end

complex matlab for loop with matrix

I don't understand this piece of code of a for loop in matlab, I know that loops in matlab usually look like: for ii=1:2:100 so that it starts in 1 until 100 and in each iteration you add 2.
But here I've got this condition in the loop and I don't get what it does:
for ii=[1:w:rd(1)-w-border, rd(1)-w-border+1],
...
end;
w and border are integers passed as arguments and rd is size of the image/matrix (rd = size(image);)
Can someone explain me how for loops work in matlab with this kind of condition?
Thanks in advance.
For loop in matlab can execute statements for a defined set of index values:
For example, the following code will display all the element in the set [1,5,8,17]:
for s = [1,5,8,17]
disp(s)
end
Your code for ii=[1:w:rd(1)-w-border, rd(1)-w-border+1] is similar.
Its just like a set 1:w:rd(1)-w-border with an additional element rd(1)-w-border+1.
Its like writing this set [1,2,3,4,5,8] as [1:1:5, 8]
I hope its clear now.
the for argument is a vector. the loop iterator ii takes one value for the vector for each iteration of the loop. As you mentioned, the vector can be equally spaced one like 1:2:100. But it can also be arbitrary, for example for ii = [4,6,1,8] ....
In you case the for argument vector is partly "equally spaced" vector: 1:w:rd(1)-w-border plus another element rd(1)-border+1.