How to insert strings in array while looping in MATLAB? - matlab

How can I insert strings in an array while looping in MATLAB? I know it's very simple but I get a mismatch error. Here is sample code.
s={'asd', 'xyzs', 'pqrs','mnopr'};
for i=1:4
w=randint(1,1,[1,2]);
switch w
case 1
word(i)=s(i);
otherwise
word(i)=3;
end
end

Your problem is that s is a cell and word is not. There are many things you can do to fix this, but an easy way would be to define word to be a cell of size(s). You would then have to convert any numbers into cells before inserting them, which means that your code would look like this:
s={'asd','xyzs','pqrs','mnopr'};
word = cell(size(s));
for i=1:4
w=randint(1,1,[1,2]);
switch w
case 1:
word(i)=s(i);
otherwise
word(i)= num2cell(3);
end
end

Related

MATLAB: If this value of 5x5 cell with vectors [106x1] are different to zeroes,count them e put the count in a matrix

I have matchcounts (5x5)cell, every cell has a vector of double [106x1]. The vectors of double have zeros and non zero values. I want to find non zero values for every cell, count them and put the result in a matrix.
I tried with this code:
a{i,j}(k,1)=[];
for k=1:106
for i=1:5
for j=1:5
if (matchcounts{i,j}(k,1))~=0
a{i,j}=a{i,j}(k,1)+1;
end
end
end
end
and others but it's not correct! Can you help me? Thanks
While it is possible to fix your answer above, I recommend to change the data structure to have a much simpler solution possible. Instead of having a 2D cell array which holds 1D data, choose a single 3D data structure.
For an optimal solution you would change your previous code code to directly write the 3D-matrix, instead of converting it. To get started, this code converts it so you can already see how the data structure should look like:
%convert to matrix
for idx=1:numel(matchcounts)
matchcounts{idx}=permute(matchcounts{idx},[3,2,1]);
end
matchcounts=cell2mat(matchcounts);
And finding the nonzero elements:
a=(matchcounts~=0)
To index the result, instead of a{k,l}(m,1) you use a(k,l,m)
To give you some rule to avoid complicated data structures in the future. Use cell arrays only for string data and data of different size. Whenever you have a cell array which contains only vectors or matrices of the same size, it should be a multidimensional matrix.

How to store variable length arrays?

I want to store an array which changes its size in each iteration of a for loop.
For example,
for y=1:100
for x=1:50
.
.
ms(:,x,y) = ans;
.
.
end
end
The 'ans' is a row vector which changes its size in each iteration of y.
How can i store these variable length 'ans' into ms?
When i try to initialize 'ms' as cell, it shows an error saying "Conversion to cell from double is not possible."
What are the ways i can solve this?
Thanks
Kind regards
The only way I can think of is to indeed use a cell array. Initialize a 2D cell array like so:
ms = cell(50,100);
After, you index into the cell by using curly braces ({}). Therefore, your loop will look like:
for y=1:100
for x=1:50
.
.
ms{x,y} = ans;
.
.
end
end
After you're done, you can index into the cell array by choosing the row and column location you want:
vec = ms{row,col};
BTW, I don't recommend you use ans as a variable. ans is the default variable that is used when you execute a statement in MATLAB which has an output and you don't specify a variable of where this output from the function will go. You may have code that will overwrite the ans variable, so you should perhaps use another name.
One way to do this:
ms = {};
for y=1:100
for x=1:50
ms = [ms 1:x];
% or
% ms = [ms new_cell_element];
end
end
You can also index the cell array with ms{x,y} = 1:3;
new_cell_element does not need to be a cell, it can be anything you want.
ms = [ms, 'A string', (1:5).'] %// Works!
Note that I do not recommend this, and I'm pretty sure there are other ways to do this, depending on what you want to do inside those nested loops. You should check out cellfun, and read up on cells in general.
Also, never ever use ans as a variable name in MATLAB. That will only cause you trouble. Any other name is better (except clear and builtin).

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;.)

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.

foreach loop with strings in Matlab

I want to create a loop that will iterate over several strings, but unable to do so in Matlab.
What works is:
for i=1:3
if (i==1)
b='cow';
elseif (i==2)
b='dog';
else
b='cat';
end
disp(b);
end
and the result is:
cow
dog
cat
But what I want is something more elegant that will look like:
for i=['cow','dog','cat']
disp (i);
end
and give the same result.
Is there an option in Matlab to do this?
ADDITION:
I need the words as strings later on to use and not just to display (the disp was just as an example). I've tried to use cell arrays in my real program:
clear all;
close all;
clc;
global fp_a
global TEST_TYPE
global SHADE_METHODE
for fp_a=11:24
for shade={'full','fast'}
SHADE_METHODE=shade(1);
for test={'bunny','city'}
TEST_MODE=test(1);
fprintf ('fp_a:%d | test: %s | shade: %s',fp_a,TEST_TYPE,SHADE_METHODE);
ray_tracing;
end
end
end
It doesn't work as the values stay as cells and not strings I get the error message:
??? Error using ==> fprintf Function is not defined for 'cell' inputs.
*-I don't really need the fprintf I just use it to check that the values are correct.
**-ray_tracing is my code that uses the values of the strings
Or you can do:
for i={'cow','dog','cat'}
disp(i{1})
end
Result:
cow
dog
cat
Your problems are probably caused by the way MATLAB handles strings. MATLAB strings are just arrays of characters. When you call ['cow','dog','cat'], you are forming 'cowdogcat' because [] concatenates arrays without any nesting. If you want nesting behaviour you can use cell arrays which are built using {}. for iterates over the columns of its right hand side. This means you can use the idiom you mentioned above; Oli provided a solution already. This idiom is also a good way to showcase the difference between normal and cell arrays.
%Cell array providing the correct solution
for word = {'cow','dog','cat'}
disp(word{1}) %word is bound to a 1x1 cell array. This extracts its contents.
end
cow
dog
cat
%Normal array providing weirdness
for word = ['cow','dog','cat'] %Same as word = 'cowdogcat'
disp(word) %No need to extract content
end
c
o
w
d
o
g
c
a
t
Sure! Use cell arrays for keeping strings (in normal arrays, strings are considered by character, which could work if all strings have the same length, but will bork otherwise).
opts={'cow','dog','cat'}
for i=1:length(opts)
disp(opts{i})
end
Use string arrays which where introduced in R2017a I believe. Note the double-quotes:
for i = ["cow", "dog", "cat"]
disp(i);
end