Creating arrays in Matlab - arrays

I want to store user inputs in an array, but when a person enters a new number, the previous input gets replaced. How can I create such an array in Matlab such that I can store all inputs without replacement? I am a beginner so bear with me
Thanks

You simply need to copy the contents of the input buffer into a data struct that won't be overwritten.
Cell arrays are good for that (see the userInputs variable below) . Without better knowledge of your code, I'm guessing the user input is stored in a variable named buffer. Here's how I would do it:
% a new buffer comes in
userInputs{iInput} = buffer;
iInput = iInput + 1;
% keep looking for more inputs
Good luck!

If you want a numeric matrix here is an example:
n = 2; %# number of rows
m = 3; %# number of columns
out = zeros(n,m); %# the output
k = 1; %# counter
while k <= n*m
x = input('Enter a number or Enter to stop: ');
if isempty(x)
break
else
out(k)=x;
end
k=k+1;
end
disp(xx)

Related

Looping through a set of sequences satisfying a certain property, without storing them

Below is a MATLAB code (recursion) which inputs a vector (l_1,l_2,...,l_r) of non negative integers and an integer m prints all sequences (m_1,m_2,...,m_r) satisfying:
0 <= m_i <= l_i for all 1 <= i <= r and m_1 + m_2 + ... + m_r = m
The r is captured in the function definition by calling the size of the (l_i) array below:
function arr=sumseq(m,lims)
arr=[];
r=size(lims,2);
if r==0 || m<0
arr=[];
elseif r==1 && lims(1)>=m
arr=[m]; %#ok<NBRAK>
else
for i=0:lims(1)
if(lims(1)<0)
arr=[];
else
v=sumseq(m-i,lims(2:end));
arr=[arr;[i*ones(size(v,1),1) v]];
end
end
end
end
Here what I have done is, stored a whole array of them and made it my output. Instead I want to only print them one by one and not store them in an array. This seems simple enough as there is not much choice in which line(s) I need to change (I believe it is the contents of the else block inside the for loop), but I get into a fix every time I try to achieve it.
(Also, MATLAB warned me that if I kept re-initializing the array with a larger array like in the statement:
arr=[arr;[i*ones(size(v,1),1) v]];
it reallocates a fresh array for all the contents of arr and spends a 'lot' of time doing so.)
In short: recursion or not, I want to save the trouble of storing it, and need an algorithm which is as efficient as or more efficient than what I have here.

How to load an ascii file into an array using actionscript 3

My friends,
As a matter of fact, I am new to AS3. What I want is to read an external text file and then load it into three arrays. The text file has 3 columns, for example, something like this
Freq Mag Phase
2000 10 56
2200 8.2 -140
2600 14 -120
... ... ...
I want three arrays, each of which contains values from each column, for example, "freqArray" should be [2000 2200 2400] I would really appreciate your help.
There are some useful pieces of code out there. I use the code below, for example, but the problem is that 1) it does not separate spaces between columns, it just separates lines 2) I guess that entries in the array are characters, not numbers.
var myLoader:URLLoader = new URLLoader(new URLRequest("myText.txt");
var myArray:Array = new Array();
myLoader.addEventListener(Event.COMPLETE, loadComplete, false, 0, true);
function loadComplete(e:Event):void{
myArray = myLoader.data.split("\n");
for(var i:int = 0; i < myArray.length; ++i){
trace(myArray[i]); // To check if it works at this point
}
//now move on with the rest of your program/code
}
I use the code below, for example, but the problem is that...
(1) It does not separate spaces between columns, it just separates lines
(2) I guess that entries in the array are characters, not numbers.
(1)
It separates by new line because of your "\n". See example reference.
If you want SPACE instead then just put a space between the quote marks.
myArray = myLoader.data.split(" ");
(2) You can convert text (written as digits) into actual Numbers by data casting.
Set int If you want whole numbers eg: myVar = int( myArray[x] ); //x holds the 2200.
Set Number If you have fraction numbers eg: myVar = Number( myArray[x] ); //x hold 8.2.
where: x is the position, inside Array, that has the value you want to cast.
A faster trick to avoid creating some new variable (myVar) might be something like...
myArray[x] = int( myArray[x] ); //just overwrite the current text chars with actual integer

Variable dimensions in file don't match with dimension of indexing subscript if one dimension is singleton

I want to test a function func(par1,par2,par3) with all combinations of the parameters par1, par2 and par3 and store the output in a .mat file. My code looks like this at the moment:
n1 = 3;
n2 = 1;
n3 = 2;
parList1 = rand(1,n1); % n1,n2,n3 is just some integer
parList2 = rand(1,n2); % the lists are edited by hand in the actual script
parList3 = rand(1,n3);
saveFile = matfile('file.mat','Writable',true);
% allocate memory
saveFile.output = NaN(numel(parList1),numel(parList2),numel(parList3));
counter1 = 0;
for par1 = parList1
counter1 = counter1 + 1;
counter2 = 0; % reset inner counter
for par2 = parList2
counter2 = counter2 + 1;
counter3 = 0; % reset inner counter
for par3 = parList3
counter3 = counter3 + 1;
saveFile.output(counter1,counter2,counter3) = sum([par1,par2,par3]);
end
end
end
This works except if parList3 has only one item, i.e. if n3 = 1. Then the saveFile.output has singleton dimensions and I get the error
Variable 'output' has 2 dimensions in the file, this does not match the 3 dimensions in the indexing subscripts.
Is there a elegant way to fix this?
The expression in the for statement needs to be a row array, not a column array as in your example. The loops will exit after the first value with your code. Set a breakpoint on the saveFile.output command to see what I mean. With a column array, par1 will not be a scalar as desired, but the whole parList1 column. With a row array, par1 will iterate through each value of parList1 as intended
Another thing is that you need to reset your inner counters (counter2 and counter2) or your second and third dimensions will blow up larger than you expected.
The n3=1 problem is expected behavior because matfile defines the variables with fixed number of dimensions and it will treat saveFile.output as 2D. Once you have fixed those issues, you can solve the n3=1 problem by changing the line,
saveFile.output(counter1,counter2,counter3) = sum([par1,par2,par3]);
to
if n3==1, saveFile.output(counter1,counter2) = sum([par1,par2,par3]);
else saveFile.output(counter1,counter2,counter3) = sum([par1,par2,par3]);
end
By now I realized that actually in matfiles all the singleton dimensions, except for the first two are removed.
In my actual programm I decided to save the data in the file linearly and circumvent matfile's lack of linear indexing capability by using the functions sub2ind and ind2sub.

store data in array from loop in matlab

I want to store data coming from for-loops in an array. How can I do that?
sample output:
for x=1:100
for y=1:100
Diff(x,y) = B(x,y)-C(x,y);
if (Diff(x,y) ~= 0)
% I want to store these values of coordinates in array
% and find x-max,x-min,y-max,y-min
fprintf('(%d,%d)\n',x,y);
end
end
end
Can anybody please tell me how can i do that. Thanks
Marry
So you want lists of the x and y (or row and column) coordinates at which B and C are different. I assume B and C are matrices. First, you should vectorize your code to get rid of the loops, and second, use the find() function:
Diff = B - C; % vectorized, loops over indices automatically
[list_x, list_y] = find(Diff~=0);
% finds the row and column indices at which Diff~=0 is true
Or, even shorter,
[list_x, list_y] = find(B~=C);
Remember that the first index in matlab is the row of the matrix, and the second index is the column; if you tried to visualize your matrices B or C or Diff by using imagesc, say, what you're calling the X coordinate would actually be displayed in the vertical direction, and what you're calling the Y coordinate would be displayed in the horizontal direction. To be a little more clear, you could say instead
[list_rows, list_cols] = find(B~=C);
To then find the maximum and minimum, use
maxrow = max(list_rows);
minrow = min(list_rows);
and likewise for list_cols.
If B(x,y) and C(x,y) are functions that accept matrix input, then instead of the double-for loop you can do
[x,y] = meshgrid(1:100);
Diff = B(x,y)-C(x,y);
mins = min(Diff);
maxs = max(Diff);
min_x = mins(1); min_y = mins(2);
max_x = maxs(1); max_y = maxs(2);
If B and C are just matrices holding data, then you can do
Diff = B-C;
But really, I need more detail before I can answer this completely.
So: are B and C functions, matrices? You want to find min_x, max_x, but in the example you give that's just 1 and 100, respectively, so...what do you mean?

How do I make a plot in Matlab if I do not know the specific size of the array?

I have some code
function runTubulin()
n = 10;
for j = 1:n
TubulinModel();
end
plot(TubulinModel(), n);
So my problem is that TubulinModel has a random number of outputs So I keep getting
??? Error using ==> TubulinModel Too
many output arguments.
Error in ==> runTubulin at 11
plot(TubulinModel(), n);
Is there A way to plot the data when I do not know the size of the array?
The error you are getting (Too many output arguments) implies that the function TubulinModel doesn't actually return any outputs. The function TubulinModel is expected to pass at least one output argument for the PLOT command to use, which it doesn't appear to be doing. You can check this by trying the following:
a = TubulinModel(); %# Place the output in a variable instead
If this gives you an error, then it means you will have to modify TubulinModel so that it returns the data you need, or places that data in a global variable that you can access outside of the function and use for the plot.
Your loop doesn't appear to do anything different with the TublinModel function on subsequent iterations. Also, the plot function calls the function again, the same way the loops did. Assuming different data of random lengths is returned by each loop, you can store each set of data in an object array, then find out what parameters to use before plotting.
function runTubulin()
n = 10;
max_length = 0; max_pos = 0; max_neg = 0;
for j = 1:n
data{j} = TublinModel(); % get your data, then characterize it
if max(data(j)) > max_pos, max_pos = max(data(j)); end
if max(-data(j)) > max_neg, max_neg = max(-data(j)); end
end
figure(1); % new axes
axis([0 10 -max_neg max_pos]); hold on; % scale the axis and freeze it
for j = 1:n
plot(length(data(j)),data(j));
end
Hope that helps!
When you call plot with two parameters, the first will be the x-axis data, and the second the y-axis data. Is this what you intend? If you want TubulinModel() to be the y-axis data, you can do plot(TubulinModel()). See help plot for more information.
I don't understand why you call TubulinModel() ten times in the loop before calling it an eleventh time in plot?

Resources