- Matrix dimension is nxn and not hardcoded.
- Nested for-loops are removed by using vectorized operations. This increases readability as well as performance of code. You can read about vectorized operations here Vectorization - MATLAB & Simulink - MathWorks India
If I want to make a code more generalize and reduce for loop what should I do? here is my code. Here in the very beginning I have written a code only to make 3X3 matrix instead of that if I want to make nXn matrix what should I do?
    6 views (last 30 days)
  
       Show older comments
    
clc
clear
A=csvread('topo.txt');
for iter=1:size(A,1)
    vec(:,:,iter)=[A(iter,2:4);A(iter,5:7);A(iter,8:10)];
end
% loop over each row
for k=1:size(A,1);
    vec_=vec(:,:,k);
%     vec_=[0 0 0;1 0 0;0 1 0];
    temp=[0 0 0];
    co=1;
    for ii=1:size(vec_,1)
        for jj=1:size(vec_,2)
            if vec_(ii,jj)~=0
                value=vec_(ii,jj);
                if vec_(ii,jj)==-1  % condition: if value is -1 use 2 instead
                    value=2;
                end
                temp(co,:)=[jj,ii,value]; 
                co=co+1;
            end
        end
    end
    % the above loop analyze the matrix
    % the following loop renames the column and row indices
    % using char(65)='A', char(66)='B'... and save file in the current
    % directory
    newfile=strcat(sprintf('%d',A(k,1,1)),'.txt');
    fileID = fopen(newfile,'w');
    fprintf(fileID,'%s %s %s\n','Source','Target','Type');
    for ii=1:size(temp,1)
        a=num2str(temp(ii,1)+64,'%s');
        b=num2str(temp(ii,2)+64,'%s');
        fprintf(fileID,'%s %s %d', a, b, temp(ii,3));
        fprintf(fileID,'\n');
    end
    fclose(fileID);
    % the following piece creates a separate directory and move the file
    newdir = sprintf('%d',A(k,1,1));
    mkdir(newdir)
    movefile(newfile,newdir)
end
0 Comments
Answers (1)
  Zinea
      
 on 23 Feb 2024
         Attached below is the code with the following changes: 
n = sqrt(size(A, 2) - 1); % Assume A has 1 column for ID and n^2 columns for matrix values 
for iter = 1:size(A,1) 
    vec(:,:,iter) = reshape(A(iter,2:end), [n, n]); 
end 
% loop over each row 
for k = 1:size(A,1) 
    vec_ = vec(:,:,k); 
    temp = []; 
    [row, col, val] = find(vec_); % Use find to get the non-zero values and their indices 
    % Replace -1 with 2 
    val(val == -1) = 2; 
    temp = [col, row, val]; % Concatenate the columns and values 
    % Add your code for write to file and create a separate directory  
end 
0 Comments
See Also
Categories
				Find more on File Operations in Help Center and File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
