For loop with set variable but slight change [duplicate] - matlab

This question already has an answer here:
Storing multiple 2d matricies in one cell array
(1 answer)
Closed 1 year ago.
Hi i am wanting to set a for loop that will create a cell array with each element of the cell array is a matrix, however the elements that i want to store in this is x1,x2,x3,x4… is there a way that I could code this such that the ith element of the array is equal to the the ith variable, ie first element of the cell array would be x1, then second would be x2 etc

Assuming that you have arrays x1 through xi, which you want to store in cell array 'X', you could use the following for loop:
for idx = 1:i
X{idx} = eval(['x' num2str(idx)]);
end
Here ['x' num2str(idx)] forms a string containing x followed by a number and eval evaluates the string as if it was a command.

Related

matlab: specify which dimension to index [duplicate]

This question already has answers here:
On shape-agnostic slicing of ndarrays
(2 answers)
Dynamic slicing of Matlab array
(1 answer)
Closed 4 years ago.
Imagine a function where you want to output a snippet in a user-specified dimension of a n-dimensional matrix
function result=a(x,dim)
window=1:10;
dim=3;
result=x(:,:,window);
end
How can I put window to the desired dimension? E.g. if dim=2; then result=x(:,window,:).
The way I can think of right now is to evaluate a string command that puts window in the correct position - or use a lot of if then else blocks. What's a better way of doing this?
You can do this using a cell array to define your indexes, following the examples here.
Specifically, if you have a matrix
x = ones(7,5,9);
You can define the indexes you want like:
% get all the indexes in all dimensions
all_indexes = {':', ':', ':'};
% get all indexes in dimensions 1 and 3, and just indices 1:4 in dimension 2
indexes_2 = {':', 1:4, ':'};
And then get those indexes from your matrix x like
a = x(all_indexes{:});
b = x(indexes_2{:});
So, you could write a function like
function result=extract_cells(x, dim, window)
% Create blank cell array {':', ':', ...} with entries ':' for each dimension
% Edit (c/o Cris Luengo): need to use ndims(x) to get the number of dimensions
num_dims = ndims(x)
dims = cell(1, num_dims);
dims(:) = {':'};
% Set the specified window of cells in the specified dimension
dims{dim} = window;
% Pick out the required cells
result=x(dims{:});
end
Which could return all the cells in the dimensions other than one specified, and in that direction would return the cells in the range given by window. So in the following code, a and b would be equivalent.
a = extract_cells(x, 2, 1:5);
b = x(:, 1:5, :)

Error while creating a function thet returns array of strings in matlab? [duplicate]

This question already has answers here:
MATLAB not enough input arguments
(2 answers)
Closed 4 years ago.
I am learning MATLAB and was trying to code the following.
Write a function called “buildrandomstrings” that will receive as input an integer n.Now If n is +ve: it will create and return a cell array with strings of random characters of increasing lengths, from 1 to n. Each string will be constituted by the previous random string plus an extra random character.
Now my code-
function buildrandomstrings = buildrandomstrings(inchar, posint)
% Creates a cell array with strings of increasing
% lengths, from 1:n, starting with inchar
% Format of call: buildstr(input char, n)
% Returns cell array with n strings
buildrandomstrings= cell(1, posint);
inchar = char(inchar-1);
strin = '';
for i = 1:posint
strin = strcat(strin, char(inchar+i));
buildrandomstrings{i} = strin;
end
end
But I am getting the following error which makes no sense to me. Even though I have looked everywhere.
buildrandomstrings(4)
Not enough input arguments.
Error in buildrandomstrings (line 7)
buildrandomstrings= cell(1, posint);
When I do ctrl+click I get the following.
Creates a cell array with strings of increasing lengths, from 1:n,
starting with inchar Format of call: buildstr(input char, n)
Returns cell array with n strings
I guess you run buildrandomstrings(4). However, you need to provide two arguments as defined by your function function buildrandomstrings = buildrandomstrings(inchar, posint).
Try:
buildrandomstrings('a', 4)
Output:
ans =
1×4 cell array
{'a'} {'ab'} {'abc'} {'abcd'}

Extracting field from cell array of structure in matlab

I have a cell array (let's say size 10) where each cell is a structure with the same fields. Let's say they all have a field name x.
Is there a way to retreive in a vector the value of the field x for all the structure in the cell array? I would expect the function to return a vector of size 10 with in position 1, the value of the field x of the structure in cell 1 etc etc...
EDIT 1:
The structure in the cell array have 1 field which is the same for all but some others which are different.
First convert your cell array of structures, c, (with identical field names in the same order) to a structure array:
c = cell2mat(c)
Then, depending on the data types and sizes of the elements of the field, you may be able to use
[c.x]
to extract your vector of field x values in the "standard" way.
It is also possible that you can skip the conversion step and use cellfun(#(e)e.x, c) to do the extraction in one go.
The below code creates a cell array of structures, and extracts field 'x' of each structure to a vector v.
%create a cell array of structures
s1.a = 'hello';
s1.x = 1;
s2.a = 'world';
s2.x = 2;
c{1} = s1;
c{2} = s2;
v = zeros(1,2);
%extract to vector
for idx=1:size(c,2)
v(1,idx) = c{idx}.x;
end
Let's say you have
c = {s1, s2, s3, ...., sn};
where common field is 'field_1', then you have two options
Use cell2mat.
cc = cell2mat(c); % which converts your cell array of structs into an array of structs
value = [cc.field_1]; % if values are number
or
value = {cc.field_1}; % if values are characters, for example
Another option is to use cellfun.
If the field values are characters, you should set "UniformOutput" to "false"
value = cellfun(#(x) x.field_1, c, 'UniformOutput', false)
The first option is better. Also, try to avoid using cell/cellfun/arrayfun whenever you can, vectors are way faster and even a plain for loop is more effecient

How to access and modify a particular value in a cell array in MATLAB? [duplicate]

C is a cell consisting of some vectors:
C = {[1, 2], [2, 3]};
I want to read the first entry of the first vector in C. But I can not use the following:
C{1}[2]
I get the following error:
Error: Unbalanced or unexpected parenthesis or bracket.
How can I make it read the value?
You can access individual elements of matrices in cell array like this:
C{n,m}(ii,jj);
This will give you element (ii,jj) of the matrix at index (n,m) of the cell array.
Hence, for your particular example,
val = C{1,1}(1,1) (or val = C{1}(1))
will assign the value of the first element of the first vector in the cell array to the variable val.

Find and delete row from cell array [duplicate]

This question already has an answer here:
Matlab - Delete row in Cell array if value contains xxx
(1 answer)
Closed 8 years ago.
A = {'A1'; 'A2'; 'A3'}
I need to find and delete row contain 'A2'(char)
Result:
A = 'A1'
'A3'
Thanks for your help!
A is not a matrix, it is a cell array.
So you may use cellfun to perform operations on cells. In your case, and in a short way:
A(cellfun(#(x) strcmp(x,'A2'), A)) = [];
I've created an anynomous function which compares the content of each cell to the string "A2"; applying this to the whole cell array gives me a mask of the cells to delete.
I would suggest you use ismember's second output for this:
[~, ind] = ismember('A2',A)
A(ind) =[]
Or in 1 line using strcmp:
A = A(~strcmp(A,'A2'))