Matlab: Export concatenation of cell arrays into a txt file - arrays

I have two different sets of arrays within an array, which I called:
y={...}; % cell array of 1x1, with a 26x1 cell array within it.
Only_Data={...} %cell array of 525x1, with 525 different 1x12 cell arrays
The data that's within the arrays is string. I want to concatenate these two arrays into one and print that final result into a .txt file. But I'm having problems doing the last part.
This is what I've done for that purpuse:
new_subject3=[y; Only_Data];
new_subject3;
outfile='mynewfile';
filename=[outfile,'.txt'];
fid=fopen(filename,'w');
[nrows,ncols] = size(new_subject3);
for row = 1:nrows
fprintf(fid ,'%s\n', new_subject3{row}{1:end});
end
fclose(fid);
For some reason I'm not aware of, it only prints the 'y' array, but doesn't print anything from the 'Only_Data' array. Why would that be? I'm clueless. I'm sure it's not about the type of data, but further than that I don't know.
I'll be glad to learn how to do this, thanks in advance.

Related

Cell array to matrix conversion in matlab

I would like to covert three <1xN cell> (A, B and C) into a single Nx3 matrix. Could someone help me with this?
C={{1xN}; {1xN}; {1xN}};
where each N is a number in single quotes, e.g.
C = {{'123123' ,'12324', ....N times}; {'123123', '12324', ....N times}; {'123123', '12324' ,....N times}}
Since a couple of them mentioned about the ridiculous input, this is the reason for having it in the above form.
The three nested array of cells are the results of a regexp where my string and expression are both strings. Therefore I have the output of regexp as three cell arrays of row vectors.
For e.g.
node_ids=regexp(nodes,'(?<=node id=")\d*','match');
I can use cat function and then use a str2double for all three cell arrays and finally form a matrix by cell2mat.
For e.g.
node_ids=cat(1,node_ids{:});node_ids=str2double(node_ids);
But this takes more time and has more LOC.
My question is can it be done with fewer lines of code?
I tried using the cat function but keep getting this error:
Cannot support cell arrays containing cell arrays or objects.
Your input data is pretty bad.... why are you using a nested array of cells where each element is a string?
In any case, assuming C is your original input data, do this:
C = {{'123123' '12324'}; {'123123' '12324'}; {'123123' '12324'}};
out = cellfun(#(x) cellfun(#str2num, x, 'uni', 0), C, 'uni', 0);
out = cell2mat(cellfun(#cell2mat, out, 'uni', 0));
First line is some dummy data. Next line first goes through every nested cell element over your cell array and converts the strings into numbers. However, these are still in cell arrays. As such, the next line converts each cell array in the nested cell into a matrix, then we merge all of the cells together into one final matrix.
We get:
>> out
out =
123123 12324
123123 12324
123123 12324

Apply a string value to several positions of a cell array

I am trying to create a string array which will be fed with string values read from a text file this way:
labels = textread(file_name, '%s');
Basically, for each string in each line of the text file file_name I want to put this string in 10 positions of a final string array, which will be later saved in another text file.
What I do in my code is, for each string in file_name I put this string in 10 positions of a temporary cell array and then concatenate this array with a final array this way:
final_vector='';
for i=1:size(labels)
temp_vector=cell(1,10);
temp_vector{1:10}=labels{i};
final_vector=horzcat(final_vector,temp_vector);
end
But when I run the code the following error appears:
The right hand side of this assignment has too few values to satisfy the left hand side.
Error in my_example_code (line 16)
temp_vector{1:10}=labels{i};
I am too rookie in cell strings in matlab and I don't really know what is happening. Do you know what is happening or even have a better solution to my problem?
Use deal and put the left hand side in square brackets:
labels{1} = 'Hello World!'
temp_vector = cell(10,1)
[temp_vector{1:10}] = deal(labels{1});
This works because deal can distribute one value to multiple outputs [a,b,c,...]. temp_vector{1:10} alone creates a comma-separated list and putting them into [] creates the output array [temp_vector{1}, temp_vector{2}, ...] which can then be populated by deal.
It is happening because you want to distribute one value to 10 cells - but Matlab is expecting that you like to assign 10 values to 10 cells. So an alternative approach, maybe more logic, but slower, would be:
n = 10;
temp_vector(1:n) = repmat(labels(1),n,1);
I also found another solution
final_vector='';
for i=1:size(labels)
temp_vector=cell(1,10);
temp_vector(:,1:10)=cellstr(labels{i});
final_vector=horzcat(final_vector,temp_vector);
end

Efficient allocation of cell array in matlab

I have some which converts a cell array of strings into a cell array of characters.
Note. For a number of reasons, both the input (C) and the output (C_itemised) must be cell arrays.
The cell array of strings (C) is as follows:
>> C(1:10)
ans =
't1416933446'
''
't1416933446'
''
't1416933446'
''
't1416933446'
''
't1416933446'
''
I have only shown a portion of the array here. In reality it is ~28,000 rows in length.
I have some code which does this, although it is very inefficient. The cellstr function takes up 72% of the code's time, as it is currently called thousands of times. The code is as follows:
C_itemised=cell(length(C),500);
for i=3:length(C)
temp=char(C{i});
for j=1:length(temp)
C(i-2,j)=cellstr(temp(j));
end
end
I have a feeling that some minor modifications could take out the inner loop, thus cutting down the overall running time substantially. I have tried a number of ways to do this, but I think I keep getting confused about whether to use {} or (), and haven't been able to find anything online that can help me. Can anyone see a way to make the code more efficient?
Please also note that this function is used in conjunction with other functions, and does work, although it is running slower than would be ideal. Therefore, I do not wish to change the format of C_itemised.
EDIT:
(A sample of) the output of my current function is:
C_itemised(1,1:12)
ans =
Columns 1 through 12
't' '1' '4' '1' '6' '9' '3' '3' '4' '4' '6' []
One thing I can suggest is to use the undocumented function sprintfc. This function is hidden from normal use in MATLAB, but it is used internally with a variety of other functions. Mainly, if you tried doing help sprintfc, it'll say that there's no function found! It's cool to sniff around the source sometimes!
How sprintfc works is that you provide it a formatting string, much like printf, and the data you want printed. It will take each individual element in the data and place them into individual cell arrays. As an example, supposing I had a string D = 'abcdefg';, if we did:
out = sprintfc('%c', D);
We get:
>> celldisp(out)
out{1} =
a
out{2} =
b
out{3} =
c
out{4} =
d
out{5} =
e
out{6} =
f
out{7} =
g
As such, it takes each element in your string and places them as individual characters serving as individual elements in a new cell array. The %c formatting string means that we want to print a single character per element. Check out the link to Undocumented MATLAB that I posted above if you want to learn more!
Therefore, try simplifying your loop to this:
C_itemised=cell(length(C));
for i=1:length(C)
C_itemised{i} = sprintfc('%c', C{i});
end
C_itemised will be a cell array, where each element C_itemised{i} is another cell array, with each element in this cell array being a single character that is composed of the string C{i}.
Minor Note
You said you were confused about {} and () in MATLAB for cells. {} is used to access individual elements inside the cell. So doing C{1} for example will grab whatever is stored in the first element of the cell array. () is used to slice and index into the cells. For example, if you wanted to make another cell array that is a subset of the current one, you would do something like C(1:3). This will create a three element cell array which is composed of the first three cells in C.

How to divide cell array into array and vector

This is my first time posting so i hope you can help me. I am trying to write a function in matlab.
I have laded data from a file into a cell array. First column contains statements and the second contains T for true og F for false. I now want to split this array into a cell array with the statements and a logical vector with 1 for True and -1 for false.
I use the fgetl within a loop to read all the lines into the cellarray
Try to write it a bit more neatly next time, and consider including a small example.
Here is what you seem to be looking for:
Suppose you have a matrix M and want to split that into M_true and M_false
M = {1,'T';
22,'F';
333,'T'}
idx_T=strcmp(M(:,2),'T')
M_true = M(idx_T,1)
M_false = M(~idx_T,1)

MATLAB using 2D Array

i want to use a 2D array to store all the values of img1, img2 and the compared vlaue of img1 and img2,
I want to achive the algorithm likes:
% read in the images from a folder one by one:
somefolder = 'folder';
filelist = dir([somefolder '/*.jpg']);
s=numel(filelist);
C = cell(length(filelist), 1);
for k=1:s
C{k}=imread([somefolder filelist(k).name]);
end
%choose any of the two images to compare
for t=1:(s-1)
for r=(t+1):s
img1=C{r};
img2=C{t};
ssim_value[num][1]=img1; % first img
ssim_value[num][2]=img2; % second img
ssim_value[num][3]=mssim; % ssim value of these two images
end
end
So, there is error about using the 2D array (ssim_value) that I used, what is the correct way of initialization it, and how to achieve the purpose that save the values that I want to store.
Could someone help me. Thanks in advance.
I'm assuming that "num" is a number that you will supply, like 5 or something. You cannot mix types in arrays as you do in Python. Also, as #Schorsch pointed out, you use parenthesis to index arrays in Matlab.
The two-dimensional array you are trying to form needs to be a 2-D cell array. For example:
a = {{"a",3},{"two",[1,2,3]};
In this case, a{1,2} = 3, and a{2,1} = "two".
You may not know in advance how many files are in the directory, so pre-initializing the cell array may not be possible in advance. In any case, Matlab arrays only need to be pre-initialized for performance reasons, and you can easily find information on initializing arrays in Matlab.
In light of this, I'm pretty sure what you are trying to accomplish is:
%choose any of the two images to compare
ssim_value = {};
for t=1:(s-1)
for r=(t+1):s
img1=C{r};
img2=C{t};
ssim_value{num,1}=img1; % first img
ssim_value{num,2}=img2; % second img
ssim_value{num,3}=mssim; % ssim value of these two images
end
end

Resources