How to read N matrixes from the keyboard - matlab

I need to save N matrixes from the user. I already save the matrix asking for how many rows and columns and iterate N times, but my question is how can I save the name of the N matrix.
Example
matrix1 = [1 2 3; 4 5 6]
matrix2 = [7 8 9; 14 15 16]
.
.
.
matrixN = [0 0 0; 0 0 0]
This is the code I have:
for k = 1:nClases
for i = 1:m(i)
for j = 1:n(i)
str = ['Ingresa elemento en fila ' num2str(i) ', columna ' num2str(j) ' de clase' num2str(k) ': ' ];
clase(i,j) = input(str);
eval(sprintf('clase%d = [1:k]', k));
end
end
end
k is the number of matrix I need.
m is the rows.
n is the columns.

I am assuming you want the user to input N matrices and don't know how to save the matrices with a given name.
You can try the following:
After a given matrix is filled out, you can do:
Matrix{k} = clase;
This will come after the i and j loops end.
At the end, you will have a cell array of matrices. To access the second one, you can just type Matrix{2}

It sounds like what you are trying to do is create a variable name for each incrementing matrix, matrix_k. The following line will return a string "filename" with the string "matrix" followed by the matrix number k:
filename = genvarname(['matrix' num2str(k)]);
You can then save the matrix with the following:
save(filename, 'matrix');
If you would like to simply assign the value of each new matrix to a new variable name, you could instead use the following:
eval(['matrix' num2str(k) '=' num2str(matrix)])
which will create a variable "matrix_k" and assign the current value of matrix to it.

Related

How to check if an element of matrices is even or not in MATLAB?

I have a problem as follows -
Script: Using ’If’ condition inside a ’for’ loop
Create a new script and save it using your name and matric ID.
Use ’for’ loop to create two matrices A and B. The size of the matrices are same, and the matrices are of 5 by 4 size.
Each element of the matrix A will be determined in the ’for’ loop using the following formula A(i,j) = a*i +b*j; where a and b are
the last two digits of your matric ID (here a = 2 and b = 5).
i and j are the row number and column number of the matrices respectively.
The elements of the matrix B will be changed from 0 to 1 ’if’ the corresponding element of the matrix A is even number.
I tried to solve in this way but it won't work. What is the correct way to check if an element is even or not in MATLAB matrices?
clc
% clear all
A = zeros(5,4);
B = zeros(5,4);
for j = 1:5
for i = 1:4
A(i,j) = 2*i + 5 * j;
if mod(B(i,j),2) == 0
A(i,j) = 1;
end
end
end
These lines in your code
if mod(B(i,j),2) == 0
A(i,j) = 1;
end
set A(i,j) to 1 if mod(B(i,j)) == 0. This is always true since you have initialized B with zeros. You shloud do it the other way around, test if mod(A(i,j),2) == 0 and set B(i,j) = 1

MATLAB - How to declare a matrix with "row slots" for me to insert rows?

In each iteration, I am inserting one row into a matrix whose row number is predetermined. My current implementation is
seqToBePutIntoMatrix = [1 2 3 4 5 6 7 8 9];
col_no = 3; % hence the matrix is 3x3
myMatrix = [];
for i = 1:col_no:length(seqToBePutIntoMatrix)
myMatrix = [myMatrix; seqToBePutIntoMatrix(i:i+col_no-1)];
end
MATLAB is suggesting me that
The variable myMatrix appears to change size in every loop iteration.
Consider preallocation for speed.
I am seriously considering its advice, and wish to preallocate such a 3-row empty matrix and insert one row in each iteration. I have tried this:
seqToBePutIntoMatrix = [1 2 3 4 5 6 7 8 9];
col_no = 3; % hence the matrix is 3x3
myMatrix = [];
j = 1;
for i = 1:col_no:length(seqToBePutIntoMatrix)
myMatrix(j) = seqToBePutIntoMatrix(i:i+col_no-1);
j = j+1;
end
However, this is not working. How may I make it work?
The subscripts myMatrix(j) references only a single element of myMatrix. In order to reference an entire row, you need
myMatrix(j,:) = seqToBePutIntoMatrix(i:i+col_no-1);
Moreover, you need to pre-allocate a 3-by-3 matrix before you start the for-loop
myMatrix = zeros(3,3);
PS,
It is best not to use i and j as variable names in Matlab.
You are still initiallizing myMatrix to an empty matrix (third line):
myMatrix = [];
To preallocate, you should initiallize the matrix to its final size:
myMatrix = NaN(3,3); %// or zeros(3,3), or ones(3,3), or ...
and then, within the loop, fill each row:
myMatrix(j,:) = seqToBePutIntoMatrix(i:i+col_no-1);

Matlab - insert/append rows into matrix iteratively

How in matlab I can interactively append matrix with rows?
For example lets say I have empty matrix:
m = [];
and when I run the for loop, I get rows that I need to insert into matrix.
For example:
for i=1:5
row = v - x; % for example getting 1 2 3
% m.append(row)?
end
so after inserting it should look something like:
m = [
1 2 3
3 2 1
1 2 3
4 3 2
1 1 1
]
In most programming languages you can simply append rows into array/matrix. But I find it hard to do it in matlab.
m = [m ; new_row]; in your loop. If you know the total row number already, define m=zeros(row_num,column_num);, then in your loop m(i,:) = new_row;
Just use
m = [m; row];
Take into account that extending a matrix is slow, as it involves memory reallocation. It's better to preallocate the matrix to its full size,
m = NaN(numRows,numCols);
and then fill the row values at each iteration:
m(ii,:) = row;
Also, it's better not to use i as a variable name, because by default it represents the imaginary unit (that's why I'm using ii here as iteration index).
To create and add a value into the matrix you can do this and can make a complete matrix like yours.
Here row = 5 and then column = 3 and for hence two for loop.
Put the value in M(i, j) location and it will insert the value in the matrix
for i=1:5
for j=1:3
M(i, j) = input('Enter a value = ')
end
fprintf('Row %d inserted successfully\n', i)
end
disp('Full Matrix is = ')
disp(M)
Provably if you enter the same values given, the output will be like yours,
Full Matrix is =
1 2 3
3 2 1
1 2 3
4 3 2
1 1 1

Assign random values from existing vector to a growing vector inside a loop

In the loop below k is assigned random integers in the interval [1, 1000].
On the first 3 loop rounds, k could be: [5], [2 6] and [5 1 5] for instance.
To a vector rnd_A, I want to assign values from a vector A, that corresponds to the k indices.
So on the third round, in the example above, I would like to get: rnd_A(1)= A(5), rnd_A(2)=A(1) and rnd_A(3)=A(5).
Is it possible to do that with one line of code or maybe two(one for dimensioning?)?
for i = 1:1000
k = randi([1,1000],[i,1]);
'assign values to rnd_A'
'do something with rnd_A'
.
.
end
Just use k to index A and assign that to rnd_A:
rnd_A = A(k);
Or, if rnd_A has more entries and you want to preserve their values, use
rnd_A(1:numel(k)) = A(k);
Suppose A is your vector:
idx = randi(length(A), 1, length(A)); % random sequence of integer as index
rnd_A = A(idx); % index into A
This is in two lines, you can make it into one line.
rnd_A = A(randi(length(A), 1, length(A)));

Creating a loop in MATLAB to find means

So I have 2 matrices in MATLAB. If one of them is a 100 X 2 matrix, like this:
[a b]
[13 19]
[21 39]
[35 45]
ect. ect.
and the other matrix is a N X 1 matrix with values like this:
[1]
[3]
[5]
[7]
ect. ect.
What I'm trying to do is find the Mean value of all the elements from 'a' to 'b' of the 2nd matrix.
What I've got so far is this:
(If my first matrix is called: MATRIX1
second matrix is called: MATRIX2)
a= MATRIX1(1:1)
b= MATRIX1(1:2)
values = MATRIX2(a:b)
mean(values)
this gives me exactly what I want, the mean of the values from a to b.
But how do I create a loop so that I can do this automatically for all the rows in MATRIX 1?
Thanks!
Update:
I figured out how to get a loop, but now I'm not sure how to take all my values and make it into a 100 X 1 matrix. This is the code I used:
c= size(MATRIX1,1);
for k= 1:c;
a= MATRIX1(k,1);
b= MATRIX1(k,2);
values= MATRIX2(a:b);
d= mean(values)
end
with this, I get 100 values of d. How do I put these values into a 100 X 1 matrix?
Here's how to do this with a for loop:
nRows = size(MATRIX1,1);
meanValues = zeros(nRows,1);
for row = 1:nRows
meanValues(row) = mean(MATRIX2(MATRIX1(row,1):MATRIX1(row,2)));
end
Another way to do this is to use the function ARRAYFUN like so:
meanValues = arrayfun(#(a,b) mean(MATRIX2(a:b)),MATRIX1(:,1),MATRIX1(:,2));
Looks like I'm already beaten, but just for the sake of variety, another option using cellfun is:
cellfun(#(pair) mean(x(pair(1):pair(2))), num2cell(inds, 2))
You are almost there!
elems = 100
values = zeros(1, elems)
for row = 1:elems
a= MATRIX1(1:1)
b= MATRIX1(1:2)
values(row) = MATRIX2(a:b)
end
mean(values)
just for clarification you want something that takes the "a"th element in matrix 2 to the "b"th element and averages all of those values?
This should work:
[r c] = size(MATRIX1);
myMeans = zeros(r,1);
for i = 1:r
myMeans(i) = mean(MATRIX2(MATRIX1(i,1):MATRIX1(i,2)))
end
this will store all of the means for the rows in myMeans